Programming With GitHub Copilot
Programming With GitHub Copilot
GitHub® Copilot
Write Better Code–Faster!
Kurt Dowswell
Copyright © 2024 by John Wiley & Sons, Inc. All rights, including for text and data mining, AI training, and
similar technologies, are reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or
by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted
under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission
of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clear-
ance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4470, or on the web
at www.copyright.com . Requests to the Publisher for permission should be addressed to the Permissions
Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008,
or online at www.wiley.com/go/permission.
Trademarks: Wiley and the Wiley logo, are trademarks or registered trademarks of John Wiley & Sons, Inc.
and/or its affiliates in the United States and other countries and may not be used without written permission.
GitHub Copilot is a trademark of GitHub, Inc. All other trademarks are the property of their respective own-
ers. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best efforts in
preparing this book, they make no representations or warranties with respect to the accuracy or completeness
of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a
particular purpose. No warranty may be created or extended by sales representatives or written sales materials.
The advice and strategies contained herein may not be suitable for your situation. You should consult with a
professional where appropriate. Further, readers should be aware that websites listed in this work may have
changed or disappeared between when this work was written and when it is read. Neither the publisher nor
author shall be liable for any loss of profit or any other commercial damages, including but not limited to spe-
cial, incidental, consequential, or other damages.
For general information on our other products and services, please contact our Customer Care Depart-
ment within the United States at (800) 762-2974, outside the United States at (317) 572-3993. For prod-
uct technical support, you can find answers to frequently asked questions or reach us via live chat at
https://support.wiley.com.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may
not be available in electronic formats. For more information about Wiley products, visit our web site at www
.wiley.com.
Creating this book has been a collaborative effort that would not have been
possible without the guidance, support, and encouragement of many people.
First, I want to express my gratitude to Kenyon Brown for believing in my
vision and providing me with the opportunity to bring this book to life.
A heartfelt thanks to Satish Gowrishankar for keeping everything on track
with meticulous planning, organization, and dedication to deadlines. Your
oversight ensured the process remained smooth and effective.
I am deeply grateful to Janet Wehner for coordinating the content and guiding
the production through each step with keen attention to detail and precision.
Special appreciation goes to T.J. Corrigan for offering invaluable expertise
and meticulously reviewing the technical aspects. Your assistance helped shape
this book into what it is today.
To my wife, Paige Lord-Dowswell, thank you for your encouragement, insights,
and acumen. You were instrumental in helping me get this book across the
finish line.
—Kurt Dowswell
iii
About the Author
v
Contents at a Glance
Introductionxvii
Part I Getting Started with GitHub Copilot 1
vii
viii Contents at a Glance
Part IV Key Insights and Advanced Use Cases for GitHub Copilot 215
Chapter 13 Considering Responsible AI with GitHub Copilot 217
Chapter 14 Augmenting the Software Development Life Cycle
with GitHub Copilot 229
Chapter 15 Exploring Copilot Business and Enterprise 253
Conclusion295
Appendix Resources for Further Learning 297
Glossary303
Index311
Contents
Introductionxvii
Part I Getting Started with GitHub Copilot 1
Chapter 1 Get Started with GitHub Copilot 3
Learn Why GitHub Copilot Matters 4
Create a GitHub Account 4
Acquire a GitHub Copilot License 4
Install an IDE Extension 5
Download Visual Studio Code 5
Install the GitHub Copilot Extension 6
Configure the IDE Settings for Copilot 7
Install Node.js 9
First Run: Test Copilot 10
Get the Prerequisites 10
Explore Copilot 10
Conclusion15
Reference15
Chapter 2 Decoding GitHub Copilot 17
Uncover the AI Behind GitHub Copilot 17
Understand Security, Privacy, and Data Handling 18
Message Transmission 19
Data Storage 19
Prompt and Suggestion Data 19
User Engagement Data 19
Additional Security 19
Vulnerability Prevention System 20
GitHub Advanced Security 20
Understand Copyright Protections 20
ix
x Contents
File Context 51
Selection Context 52
Commanding Your Conversation with Precision 52
Querying with @workspace 53
Learning with /explain 53
Generating Tests with /tests 56
Finding a Fix with /fix 59
Scaffolding with /new 61
Crafting with /newNotebook 62
Engaging with @vscode 63
Inquiring with /api 64
Learning with @terminal 64
Conclusion65
Part III Practical Applications of GitHub Copilot 67
Chapter 5 Learning a New Programming Language 69
Introducing Language Education with Copilot 70
Setting Up Your Development Environment 70
Prerequisites70
Setup Guide 70
Learning the Basics 72
Prerequisites72
Learning C# with Copilot 73
Creating a Console Application 74
Prerequisites74
Creating a C# Console Application with Copilot 74
Explaining Code with Copilot 77
Adding New Code 78
Learning to Test 79
Creating Context with Selection 82
Creating Context with Tags 84
Running Tests 84
Conclusion85
Reference86
Chapter 6 Writing Tests with Copilot 87
Establishing the Example Project 87
Prerequisites88
Adding Unit Tests to Existing Code 89
Driving Unit Test Creation with Comments 89
Using Inline Chat to Generate Tests 93
Exploring Behavior-Driven Development with Copilot 94
Adding User Accounts 95
Setup95
End-to-End Tests 96
Conclusion99
xii Contents
xvii
Par t
I
Getting Started with
GitHub Copilot
In This Part
Chapter 1: Get Started with GitHub Copilot
Chapter 2: Decoding GitHub Copilot
CHAPTER
3
4 Part I ■ Getting Started with GitHub Copilot
■■ Copilot Individual
■■ Copilot Business
■■ Copilot Enterprise
There are several factors to consider when choosing the correct plan. If you
are a student or a maintainer of a popular open-source project, you might be
eligible for a free Copilot Individual license.
You can get more information on licenses on this web page:
https://docs.github.com/enterprise-cloud@latest/billing/
managing-billing-for-github-copilot/about-billing-for-github-copilot
NOTE In this book, we will be using the Visual Studio Code IDE for most of the
examples. If you use one of the other supported IDEs as your preferred development
platform, the information shared in these examples will be transferrable. We will be
covering these additional IDEs later in the book when we detail how to set up and con-
figure them to work with GitHub Copilot.
Once you have installed VS Code on your computer, you should see a welcome
screen (see Figure 1.1).
6 Part I ■ Getting Started with GitHub Copilot
Install Node.js
Lastly, Node.js will need to be installed to run the example. Node.js is an open-
source, cross-platform, back-end JavaScript runtime environment. It allows us
to execute JavaScript outside of the web browser.
The easiest way to install Node.js is to go to the website:
https://nodejs.org/en/download.
Based on your operating system and computer hardware, select the appro-
priate download, and follow the installation steps.
After installing Node.js, run the following command in your terminal to
confirm that you have installed it successfully.
node -v
This command will output the node version you have installed.
10 Part I ■ Getting Started with GitHub Copilot
Explore Copilot
Let’s make sure that Copilot is working by writing a quick example function.
In this section, you will create a palindrome checker to showcase some of the
basic interactions you will have with Copilot within your editor.
Start by opening a folder in VS Code. You can do this via the Explorer menu
(see Figure 1.6) or the keyboard shortcut (Cmd+O/Ctrl+O).
NOTE Throughout this book, keyboard shortcuts will be displayed for both macOS
and Windows OS.
Create a new folder called copilot-test and click Open within your Finder/
Explorer window.
Add a new file to your open folder called palindrome-checker.js (see
Figure 1.7).
Now you are ready to start writing the Node.js script. Let’s start by typing a
top-level comment in the palindrome-checker.js file, as shown here:
// node.js application that checks if a string is a palindrome
Chapter 1 ■ Get Started with GitHub Copilot 11
As you start writing this comment, Copilot should start suggesting some text
to complete it (see Figure 1.8).
You can accept the Copilot text completion by hitting the Tab key.
NOTE You can provide context to Copilot in several ways, such as descriptive file
comments, inline comments, examples, filenames, imports, method names, variables,
and open file tabs. You will see all these context types in action throughout this book.
With the comment at the top of the file, continue to the next line. You can pro-
vide additional context by adding some examples of palindromes you would
like the checker to expect to receive.
// examples: racecar, taco cat
Without this example comment, there is a chance that the palindrome function
will not account for phrase inputs. Adding this context is a way for you to
continue to refine the context given to Copilot to get better output.
Chapter 1 ■ Get Started with GitHub Copilot 13
Now that you have a short, clear, and targeted comment for your file, you can
add two line returns to the file to move on to the function implementation. If
Copilot doesn’t automatically give you the line you would like as a suggestion,
you can start typing the statement you would prefer. Copilot will then use this
additional context to drive a better completion suggestion for the current line
you are working on.
In my case, I will accept a line comment describing a function to check if a
string is a palindrome and implement the first line of the function name (see
Figure 1.9).
NOTE GitHub Copilot is nondeterministic and may return different results for you
even though you have the same comment structure within your file. We will cover the
AI behind Copilot in depth in Chapter 2, “Decoding GitHub Copilot.”
You can continue to accept and refine code completions provided by Copilot
in the file. Accept suggestions with the Tab key or use the menu if available
when hovering on the suggestion text.
14 Part I ■ Getting Started with GitHub Copilot
After coding the isPalindrome function, you can continue to add some test
cases. Copilot will most likely suggest continuing. But to ensure you get the
output you want, add another line comment.
// test cases
After you add a new line, Copilot should start completing the test cases using
the examples from the top-level file comment. Continue implementing these
test cases (see Figure 1.10).
With the function and tests, you can now run this file to see if you get the
expected output. If you are following along in VS Code, you can open the
integrated terminal to run the function via the keyboard shortcut (Ctrl+`).
Within the integrated terminal that is open to the current location of your
Node.js file, type the following to run the function:
node palindrome-checker.js
You should now see output indicating the expected results from your function
(see Figure 1.11).
Chapter 1 ■ Get Started with GitHub Copilot 15
Conclusion
There are a multitude of ways in which GitHub Copilot will assist you in your
developer workflow. So far, we have only scratched the surface of the capabil-
ities Copilot provides. Up next, you will learn more about GitHub Copilot code
suggestions, what data sources and training it uses, and privacy and security
considerations that are important to know.
Reference
In this chapter, we will look at the AI behind GitHub. We will explore the genesis,
advancement, and capabilities of GitHub Copilot. We’ll delve into the security
and privacy measures that safeguard our work, highlighting the importance
of secure data handling and the mechanisms in place to protect our code. We
will also explore the critical topic of copyright protections, ensuring that our
use of GitHub Copilot aligns with legal standards. Lastly, we will review the
GitHub Copilot Trust Center to equip ourselves with the necessary knowledge
to navigate the complexities of using this powerful tool confidently.
■■ Uncover the AI Behind GitHub Copilot
■■ Understand Security, Privacy, and Data Handling
■■ Understand Copyright Protections
17
18 Part I ■ Getting Started with GitHub Copilot
GitHub Copilot was first conceptualized in 2020 after GPT-3 was released.
The GitHub team had routinely asked, “Should we think about general-purpose
coding generation?” But the answer was always no. Until GPT-3, the ability to
produce high-quality code suggestions in the required development scenarios
was nonexistent [1]. Once the team got their hands on the GPT-3 model, they
rapidly discovered that GPT-3 could perform at a very high level for code gen-
eration tasks.
Building on top of the already powerful GPT-3 model, in 2021, GitHub and
OpenAI worked closely together on a new OpenAI model that was a descendant
of GPT-3. The model was called OpenAI Codex. The Codex model was trained on
billions of lines of code from publicly available sources as well as public GitHub
repositories. The combination of the impressive general-purpose language model
(GPT-3) and the massive code training dataset allowed the team to improve the
capabilities of GPT-3 even further to interpret natural languages, like English
and Spanish, into programming languages, such as JavaScript, Python Go,
Perl, PHP, and more. This newfound ability to bridge the gap between natural
languages and programming languages resulted in the Codex model having
the capability to perform transpilation, explain the purpose of code files, and
even refactor existing code based on the request of the prompt statement [2].
This technology is the bedrock of the GitHub Copilot code suggestion engine.
Since the advancements of the OpenAI Codex model, GitHub has been iter-
ating consistently on innovative ways to integrate Copilot into the software
development lifecycle. On December 29, 2023, GitHub Copilot Chat, powered
by GPT-4, was released to all GitHub Copilot users. Copilot Chat is built on a
mosaic of technologies working in concert to provide end users with bespoke
expert advice when navigating the complexities of their codebases. With the
combination of the OpenAI GPT-4 LLM, GitHub knowledge graph, local code-
base indexing, language intelligence, and a processing pipeline, Copilot Chat
can converse with you about your codebase and give verifiable and action-
able responses empowering you to navigate your way to solutions with less
friction and more fun.
Looking to the future, GitHub will continue to improve the AI behind Copilot.
With the constant advancement in AI models, the team at GitHub will ensure
you are receiving the most recent powerful model updates to keep you com-
petitive in an ever-changing development landscape.
Message Transmission
When interacting with GitHub Copilot, all the required context to resolve your
questions or completion suggestions must be transmitted to GitHub’s services
running on Azure. This data is passed via Hypertext Transfer Protocol Secure
(HTTPS) over Transport Layer Security (TLS). This end-to-end encryption pro-
cess ensures your data, code, and queries are all secure and processed only by
the GitHub Copilot back-end services. HTTP over TLS is the global standard
for safe and secure message passing.
Data Storage
In this section, we will detail what GitHub Copilot data is stored at rest.
Additional Security
In this section, we will cover the vulnerability prevention system and GitHub
Advanced Security. It is important to note that you should always rely on addi-
tional security tooling like GitHub Advanced Security to ensure you are not
injecting vulnerabilities for production codebases.
20 Part I ■ Getting Started with GitHub Copilot
The LLM will then process these token inputs and identify the pattern that is
occurring. This will result in a predicted token that should occur next, which,
in this case, is 5.
Building on the numeric list example, let’s see how this works when we are
coding a new method. If we have a Python function declaration such as this:
def greet(name):
Chapter 2 ■ Decoding GitHub Copilot 21
then Copilot will split out our function declaration into a series of tokens:
[‘def’, ‘greet’, ‘(‘, ‘name’, ‘)’, ‘:’]
The LLM will then process these token inputs and identify the pattern that
is occurring. This will result in a predicted token that should occur next. In this
case, the token most likely would be print.
The model then continues to predict the next tokens, resulting in a completed
line of code.
def greet(name):
print(f"Hello, {name}!")
While the code is not saved to the model, due to the way in which the training
operations are conducted, there is a chance (less than 1%) that Copilot will pro-
duce results that match the code used to train the model [3]. It is important to
understand that this is not copy-and-pasting. It is determining the best chain
of code that matches the prompt and context it is operating within.
GitHub, with the support of its parent company Microsoft, has always provided
copyright indemnification protections ensuring that you will be protected if
any legal action is brought against you because of the use of GitHub Copilot.
At the Ignite conference in November 2023, Microsoft expanded its copy-
right support to all of its generative AI solutions and tools, further entrenching
Microsoft’s support to customers in this area. This commitment is called the
“Customer Copyright Commitment (CCC),” and it ensures that all customers
using Microsoft generative AI solutions are backed by the legal support of
Microsoft if faced with legal issues.
NOTE You must have the GitHub Copilot Policy setting called Suggestions Matching
Public Code set to Blocked to be eligible for this legal protection. For more information,
please see this page:
https://learn.microsoft.com/en-us/legal/cognitive-services/
openai/customer-copyright-commitment
Conclusion
In this chapter, our exploration of GitHub Copilot has unveiled the remarkable
AI driving this innovative tool, emphasizing its development, security mea-
sures, and commitment to copyright compliance. Through understanding the
intricate layers of protection and legal foresight integrated into GitHub Copilot,
alongside the resources available in the Trust Center, we are now better posi-
tioned to leverage this technology. As we move forward, equipped with this
knowledge, we can confidently incorporate GitHub Copilot into our development
workflows, harnessing its potential to streamline our coding processes and
enhance our productivity.
References
[1] S. Verdi, 2023. “Inside GitHub: Working with the LLMs behind GitHub
Copilot,” https://github.blog/2023-05-17-inside-github-working-
with-the-llms-behind-github-copilot
[2] OpenAI, 2021. “OpenAI Codex,” https://openai.com/blog/openai-codex
[3] GitHub, 2023. “GitHub Copilot Trust Center,” https://resources.github
.com/copilot-trust-center
Par t
II
GitHub Copilot Features
in Action
In This Part
Chapter 3: Exploring Code Completions
Chapter 4: Chatting with GitHub Copilot
CHAPTER
In this chapter, we will do a deep dive into the code completion capabilities of
GitHub Copilot. We will cover all the details you need to get the most out of
Copilot code completions. While code completions are incredibly intuitive, we
will explore various features that will enable you to create more refined solu-
tions that meet the needs of your development plan.
■■ Introducing Code Completions
■■ Working with Copilot Code Completions
■■ Discovering the Toolbar and Panel
25
26 Part II ■ GitHub Copilot Features in Action
you in writing code faster, refactoring code, writing code you are unfamiliar
with, creating documentation, and even writing unit tests!
Code completions are accessible right within your IDE editor window.
These code suggestions can be accepted as a whole, by line, or by word. The
length of the code completions can vary based on the location you are currently
typing. Let’s dive into the details and understand how to best utilize Copilot
code completions.
Prerequisites
To follow along with this example, you will need the following prerequisites
installed:
■■ Visual Studio Code:
https://code.visualstudio.com/download
■■ GitHub Copilot Extension:
https://marketplace.visualstudio.com/items?itemName=GitHub.
copilot
■■ Node.js:
https://nodejs.org/en/download
Top-Level Comment
Building on the filename and type, you can add a filename comment to your
code file to add more context to Copilot’s decision engine.
Chapter 3 ■ Exploring Code Completions 27
After typing this comment, hit the Enter key and wait for Copilot to respond
with a code completion suggestion. If you don’t see one, you can initiate a
response with the keyboard shortcut (Option+\ or Alt+\), as shown in Figure 3.1.
Accept the response from Copilot with the Tab key. Continue to hit the Enter
key to progress down your file and allow for Copilot to respond with additional
code that meets the needs of your top-level comment (see Figure 3.2).
NOTE Always verify the output provided by Copilot for accuracy and secure
coding practices.
28 Part II ■ GitHub Copilot Features in Action
Continue to accept the responses and write the remainder of the roman-
to-integer.js code that is required for the file to run successfully. After you
have completed the code completions and writing, the file should contain
a readline import, readline variable, readline question and answer, and
romanToInt function.
Now you should be able to run the js file via Node. Open your terminal via
the keyboard shortcut (Ctrl+`) or with the command menu (see Figure 3.3).
Now, within the terminal window, type the following:
node roman-to-integer.js
Hit the Enter key, and you should see the prompt from the Node.js app,
allowing you to provide a Roman numeral.
This should have provided you with a working example of an application that
can convert Roman numerals to integers. In the next section, we will explore
how you can expand upon this example using other methods of the code com-
pletion feature set.
Chapter 3 ■ Exploring Code Completions 29
Accept the Copilot suggestions and press Enter and Tab until you have com-
pleted the isRomanNumeral() function. After you have the completed function, pro-
ceed to the terminal again and run the application with the following command:
node roman-to-integer.js
You should now be able to see your validation method in action, with
output shown to the user if they were to input an incorrect Roman numeral
(see Figure 3.6).
Hit the Enter key after this comment and wait for Copilot to respond with a
suggestion. If Copilot does not initiate a code completion suggestion, you can
manually trigger this by using the keyboard shortcut (Option+\ or Start+\).
You should get something like Figure 3.7.
You can see this in action by creating a new file in VS Code. Let’s call the new
file integer-to-roman.js. In this file, we will start with a top-level comment
to provide context to Copilot about our intent within this file (see Figure 3.8).
Add the following comment to the top of this file:
// Integer to roman numeral app
After entering the top-level comment, hit the Enter key and begin to review
and accept the code completions that Copilot is providing. You will see Copilot
adapting the code to meet the need of this new file while following the coding
design of the open roman-to-integer.js tab.
After you have accepted and refined the code completions, you can now exe-
cute this Node application. Here you will find that Copilot has conformed to
your coding style from the referenced document, understood your intent with
your new file based on the filename and top-level comment, and produced a
well-crafted output for you to refine further and iterate on as you see fit.
34 Part II ■ GitHub Copilot Features in Action
Whenever Copilot has multiple potential solutions to the next code, this
toolbar is useful if you’d like to iterate quickly over potential options via the
arrow buttons on the left side of the toolbar. The toolbar also allows you to
accept the entire suggestion (Cmd+Tab/Ctrl+Tab) or accept a single word at a
time (Cmd+Right Arrow/Ctrl+Right Arrow).
Chapter 3 ■ Exploring Code Completions 35
If you’d like to accept an entire line or adjust the toolbar’s default visibility,
you can find these options within the ellipsis menu on the right.
Here you can adjust settings such as file type enable settings, locale overrides,
chat preferences, and more.
Within the VS Code advanced settings (see Figure 3.12), you can update a
variety of settings to customize your Copilot responses. I will detail a few of
the settings available for you to alter. Please note that these settings are valid
only for VS Code.
NOTE Edit these settings only if necessary. The default behaviors of Copilot have
been tuned for the best user experience, and altering them may diminish the quality of
the Copilot responses.
Chapter 3 ■ Exploring Code Completions 37
inlineSuggestCount
Update this value if you would like to control the maximum number of inline
suggestions that are produced.
length
The length setting allows you to specify a maximum length for code sugges-
tion responses.
listCount
The listCount setting (Ctrl+Enter) controls the limit of code suggestions that
you will be shown.
38 Part II ■ GitHub Copilot Features in Action
Conclusion
In this chapter, we have covered in detail GitHub Copilot’s code completion
capabilities, which are crucial for enhancing your coding efficiency and creativity.
By introducing code completions, demonstrating how to work with Copilot,
discovering its toolbar and panel, reviewing settings, and leveraging keyboard
shortcuts; this chapter empowers you with the knowledge to harness Copilot’s
potential. As we’ve seen, Copilot is more than just a tool for generating code;
it’s a partner in your development process, enabling the creation of refined
solutions that align with your unique development goals.
CHAPTER
While code completions allow for tightly integrated responses to keep you in
the flow of coding, Copilot Chat enables you to have robust conversations about
your code in an intuitive way. Copilot Chat can help you understand code, learn
new topics of interest, refine code files, write tests, create documentation, and
learn the features of Copilot.
Let’s dive in to the things that you need to know to get working with
Copilot Chat!
■■ Discovering Copilot Chat
■■ Defining Prompt Engineering with Copilot Chat
■■ Commanding Your Conversation with Precision
41
42 Part II ■ GitHub Copilot Features in Action
In this example, you will see that you can ask Copilot questions about the
current editor tab that is visible to the right using the following statement:
/explain #editor
The @workspace agent keyword will be automatically injected into the prompt
when you type the /explain command.
Chat In Editor. Also, within the Copilot sidebar chat window, you can move
your conversation to the editor view using the ellipsis menu at the top right
and selecting Open Chat In Editor.
NOTE Each conversation tab or window with Copilot is separate from one another.
This means the chat prompts and responses are not used by other chat instances.
In addition to this quick chat experience, GitHub Copilot is also available via
an extension for the GitHub command-line interface (CLI). We will cover this
in depth later in the book.
Define a class for a vehicle that has properties such as make, model,
and year in Python
What are some best practices for optimizing SQL queries in Python?
Do you have any recommendations for libraries that can simplify parsing
JSON in Java?
What are the best practices for managing state in a React application?
Editor Context
In VS Code, to give Copilot context to the file you are currently editing, use the
#editor tag in your prompt (see Figure 4.11). This will give Copilot the code
you are currently viewing in your editor as context.
Chapter 4 ■ Chatting with GitHub Copilot 51
In other IDEs, the #editor tag may not be available, even though the Copilot
team attempts to align features and user experiences whenever possible.
In this example, we used the following prompt:
@workspace /explain #editor
This allows us to get a full definition of the code within the editor window.
File Context
If you don’t have the file open that you know you want an answer about, you
can use the #file tag to specify the file you would like to have considered. You
can also use the #file tag for multiple files within a single prompt if necessary
(see Figure 4.12).
In the previous example, when we enter #file, we will see a menu appear.
Select that option, and you will then see a search box to find the appropriate
file. After selecting your file, you will see the #file tag with the associated file
in your prompt.
Adding context via the #file tag may differ from one IDE to the next. The
Copilot team attempts to align features whenever possible.
52 Part II ■ GitHub Copilot Features in Action
Selection Context
When interacting with Copilot via a chat window, if you have text selected in
your editor, Copilot will automatically use that code as context for the prompt
that you send.
You can also specify declaratively to Copilot that you would like it to consider
the selected text by using the #selection tag.
Currently, this tag is implemented only in VS Code. In the future, this
may change.
Now within the file editor, you can activate inline chat (Cmd+I/Alt+I) and
type / to get a list of the available commands within the inline chat dialog. You
can now select the /explain command. If you have a question about code you
are working on, make sure to select the code in question before sending your
question to Copilot (see Figure 4.14).
If you prefer, you can also Copilot questions about your code from the sidebar
chat window. Just make sure to highlight the code you would like to have
explained (see Figure 4.15).
Copilot is also able to give you a full explanation about the current file you
are reviewing. To do this, simply use the #editor tag in your prompt to indicate
to Copilot that you would like to have it consider the visible section of your
working document.
Working within the terminal is deeply engrained in the workflows of devel-
opers all over the world. But when something goes wrong within your terminal,
or you don’t understand an error that has occurred, lean on Copilot to assist
you in getting an answer quickly and bespoke to your pressing needs. When an
error occurs, you can use the sparkle icon as your quick path to an explanation
by Copilot (see Figure 4.16).
Chapter 4 ■ Chatting with GitHub Copilot 55
If you don’t have the quick fix menu available, you can highlight the terminal
lines in question and use the Copilot menu to initialize a quick chat with Copilot
to get an answer in a snap (see Figure 4.17).
Another option to generate tests is to use the inline chat dialog with your
method selected that you would like tests created for (see Figure 4.19).
Using this inline chat /tests command will result in an inline preview of
assertion methods that you can review and accept.
NOTE You can guide Copilot into creating better unit tests by having an example
file open with existing unit tests that match the structure you would like. Also, you can
include prompt details like the type of tests you would like or the testing libraries that
should be used.
Within the chat window with Copilot, you can use the /tests command as
well. You still need to provide Copilot with the context of your preferred test
method by selecting it, or you can reference the visible section of the editor via
the #editor tag (see Figure 4.20).
After you have executed the /tests command with one of the methods shown
previously, you should end up with output that allows you to start testing your
method to ensure it is functioning properly (see Figure 4.21).
58 Part II ■ GitHub Copilot Features in Action
With this test file, you can see that Copilot has created a good list of assertions
that will ensure you have a well-functioning method. From this starting point,
you can add assertions for floating-point numbers, strings, and nonarray input
values. You can use code completions or chat to brainstorm additional test cases
that you would like to add.
You can see that Copilot has provided a code modification for you, along
with a justification of the fix action taken.
If the response provided is not up to par with what you expect, you can dis-
card the change, iterate on another alternative, or respond with feedback to help
train Copilot in the future with the Helpful and Unhelpful response buttons.
With this request submitted, you will see a response from Copilot with a
suggested workspace structure (see Figure 4.24). This structure will align with
your initial request and combine it with the project standards for the language
and any additional details you provided in the request.
After reviewing the proposed workspace scaffolding, you can click Create
Workspace, find your parent folder for the project, and then allow Copilot to
generate the contents of each file in the project. This will result in a solid starting
point to work from. In this case, we’ve created a functional game of Rock Paper
Scissors with unit tests covering our game.
Copilot now generates all the sections and inserts starter code for our tasks
of data analysis (see Figure 4.26).
You are now empowered to iterate on this initial design and start working
on solutions!
Conclusion
In this chapter, we have meticulously explored the diverse interaction mech-
anisms available with Copilot via Chat, offering a comprehensive guide to
harnessing this powerful tool within the development workflow. By navigating
through sidebar conversations, editor views, inline queries, and the strategic
use of context-specific tags, we have uncovered the depth of Copilot Chat’s
capabilities in understanding and assisting with coding tasks. This detailed
examination not only sheds light on the versatility and adaptability of Copilot
Chat but also underscores its significance as an intelligent assistant that can
enhance coding efficiency, facilitate problem-solving, and foster a more intui-
tive coding environment.
Leveraging the insights from this chapter, you can capitalize on the full spec-
trum of functionalities offered by Copilot Chat. Whether it’s refining code,
debugging, writing tests, or generating documentation, Copilot Chat stands
ready as a collaborative partner, equipped to navigate the complexities of soft-
ware development alongside you.
Par t
III
Practical Applications of
GitHub Copilot
In This Part
Chapter 5: Learning a New Programming Language
Chapter 6: Writing Tests with Copilot
Chapter 7: Diagnosing and Resolving Bugs
Chapter 8: Code Refactoring with Copilot
Chapter 9: Enhancing Code Security
Chapter 10: Writing Tests
Chapter 11: Enhancing Development Environments with Copilot
Chapter 12: Universal Conversion with GitHub Copilot
CHAPTER
5
Learning a New Programming
Language
In this chapter, we will explore how you can interact with Copilot to learn a new
programming language. With Copilot, you can quickly get answers to questions
about languages, gain bespoke insights based on your previous knowledge, get
examples, run tests, and ask questions as you learn, all within the integrated
development environment (IDE)!
The chapter will be using VS Code to showcase how to learn with GitHub
Copilot and will be using Copilot Chat extensively. It is important to note that
Copilot Chat is not available in all IDEs. In addition, the Chat experience is
slightly different from one IDE to another. Although there are differences, most
of the information shared will be transferrable to other IDEs.
■■ Introducing Language Education with Copilot
■■ Setting Up Your Development Environment
■■ Learning the Basics
■■ Learning to Test
69
70 Part III ■ Practical Applications of GitHub Copilot
Prerequisites
To follow along with this example, you will need the following prerequisites
installed:
■■ Visual Studio Code
■■ GitHub account with Copilot plan
■■ VS Code GitHub Copilot extension
Setup Guide
The first thing you need to do when learning a new language is ensure that your
development environment is configured properly. In the example you will see
in this chapter, you will be learning the C# programming language.
Let’s leverage Copilot Chat to help set up the environment. The following
will get Copilot to guide us to the necessary resources and steps to get started
(see Figure 5.1):
help me setup my computer to run c#
Chapter 5 ■ Learning a New Programming Language 71
After you have installed the .NET Core SDK to enhance your developer
experience within VS Code, it is helpful to have the C# extension as Copilot has
indicated in the setup instructions. If you are not in VS Code, you will still be
able to run the C# application using the dotnet command-line interface (CLI).
Let’s navigate to the Extensions panel on the Action Bar. You will find the
Extensions panel identified by the “squares” icon (see Figure 5.2).
1. Open the Extensions panel.
2. Search for “C#.”
3. Within the “C#” extension result, click Install.
Microsoft encourages you to install the C# Dev Kit, which contains the C#
extension. For the purposes of this demo, you will just need the C# extension.
But if you are interested, exploring the features of a rich developer experience
via the C# Dev Kit might interest you.
72 Part III ■ Practical Applications of GitHub Copilot
Prerequisites
To follow along with this example, you will need the following prerequisites
installed:
■■ Visual Studio Code:
https://code.visualstudio.com/download
■■ GitHub Copilot extension:
https://marketplace.visualstudio.com/items?itemName=
GitHub.copilot
■■ GitHub account:
https://github.com/signup
■■ GitHub Copilot license:
https://github.com/features/copilot/plans
Chapter 5 ■ Learning a New Programming Language 73
NOTE GitHub Copilot is nondeterministic and may return different results for you
even though you have the same prompt text.
follow-up questions at the bottom of the chat response based on the previous
context of the conversation.
Prerequisites
To follow along with this example, you will need the following prerequisites
installed:
■■ Visual Studio Code (VS Code)
■■ GitHub account
■■ GitHub Copilot license
■■ GitHub Copilot extension
■■ .NET Core SDK
■■ VS Code C# extension
When giving instructions to Copilot, context and clarity are critical for you
to receive the output you would like. In this case, specifying the dotnet version,
language, project name, and test framework gave Copilot the context needed
to give you a great result.
Now let’s explore how you can converse with Copilot to discover how to cre-
ate a C# console application and run it manually. Remember, you can create a
prompt specific to your topic of choice so that Copilot gives you instructions that
are targeted to you. Try prompting Copilot with something like the following:
How do I create a c# console app and run it?
Chapter 5 ■ Learning a New Programming Language 75
With this prompt to Copilot Chat, you should get a result indicating the
steps required to run a C# program in VS Code. This will include things like
the following (see Figure 5.4):
1. Install the .NET Core SDK.
2. Open VS Code.
3. Open the terminal in VS Code.
4. Navigate to the directory you want to create your project in.
5. Create a new console application with the dotnet CLI with a command
such as dotnet new console - n PiratesExample.
6. Navigate to your new project in the terminal with the cd PiratesExample
command.
7. Open your project in VS Code with the code . command within the ter-
minal window.
After following these steps, you should have a VS Code window with the
pirate example project created (see Figure 5.5).
With the example C# application, you can now continue to add code to explore
the language features of C#. Let’s open Copilot Chat to get a Pirate class started
so that you can learn more.
After opening Copilot Chat, you can enter a prompt like the following:
Create a C# Pirate class with name, age, and ship properties
This prompt adds enough context about your technology and language of
choice to produce a consistent result. The less context you provide Copilot, the
more freedom it will have in giving you responses. In this case, you should
see something like Figure 5.6). With this response code, you should be able to
create a Pirate.cs class from the code generated by Copilot.
Chapter 5 ■ Learning a New Programming Language 77
Figure 5.7: Copilot /explain chat command for Pirate class file
This will result in Copilot providing you with a new method Insert of code sug-
gestion that enables you to quickly extend the functionality of the Pirate.cs class.
Chapter 5 ■ Learning a New Programming Language 79
Learning to Test
With any programming language, it is critical for you to understand how you
can effectively test your code. Each language and framework has different testing
methodologies. In this section, you will explore how you can leverage Copilot
to help guide you in learning C# testing methodologies.
Before getting started with adding your unit tests, you should move your
existing project files into a new child folder. You can do this by creating a new
folder in your workspace called PiratesExample. Then, simply cut and paste
your Pirate.cs, PiratesExample.csproj, and Program.cs classes into the
PiratesExample folder.
As we have done in previous sections, let’s ask Copilot how we can learn a
new aspect of the language we are learning. In this case, you will ask Copilot
how you can create unit tests for the C# pirate example project (see Figure 5.9).
Here’s the example prompt:
@workspace How can I create unit tests for my C# program using the
dotnet cli?
80 Part III ■ Practical Applications of GitHub Copilot
In this case, Copilot returned a result indicating that there are multiple types
of testing frameworks. And the example CLI command that was given uses the
NUnit testing framework. Instead of using the suggested command, you can
aso explore the pros and cons of each of the testing frameworks available with
Copilot to ensure that you are making the best choice for the project you are
working on. In our example, we will continue with our suggested dotnet CLI
command using NUnit.
When using the @workspace agent within VS Code, Copilot will index our
codebase and scan for relevant files that will help generate a better response.
Copilot chat agents do not exist in all IDEs. If you are working in another IDE,
you will need to specify additional context in your prompt to get a similar
output. Agents allow you to get quality results tailored to your needs without
having to research and construct robust prompts.
Within the Copilot response for creating unit tests, it suggested that we create
a new project for our tests. If you are new to C#, it might not be immediately
obvious why this is the suggested pattern. Thankfully, you can ask Copilot why
this was suggested. Use the following prompt:
Why is it important to have our unit tests in a separate project?
Chapter 5 ■ Learning a New Programming Language 81
Copilot will respond with several valid reasons to this common practice,
including separation of concerns, avoiding deployment of test code, dependency
management, build performance, and organization considerations.
Copilot Chat within VS Code allows you to copy code snippets to your clip-
board, insert code into your current file, create a new file, or insert code into
the terminal. Here you can leverage the insert into terminal functionality (see
Figure 5.10).
After you run the command dotnet new nunit -n PiratesExample.Tests,
the PiratesExample.Tests project should be created.
You can then follow Copilot’s next suggestion to add a reference to the
PiratesExample project. Enter the following command into the terminal:
Copilot should have suggested how to run our unit tests project. If it hasn’t,
you can ask for a dotnet CLI command to run unit tests, and you should be able
to see the command for this is dotnet test. After running this, you will see an
error indicating the working directory does not contain a project or solution
due to us moving out of the PiratesExample project. You can use the quick-fix
82 Part III ■ Practical Applications of GitHub Copilot
menu and have Copilot give you a justification and potential fix for the terminal
issue we have encountered (see Figure 5.11).
Figure 5.11: Copilot explaining the last terminal command via a quick-fix menu
Now that you know how to properly run the dotnet test command, you
can run it and get a successful build and run of the test project (see Figure 5.12).
With the unit test project now running, you can have Copilot create a starting
point for exploring how to test the Pirate.cs class. Let’s begin by opening the
Pirate.cs file. To create a test for the Greeting() method, it is important to
give Copilot the context it needs in order to create a quality starting point for
the test file. You can do this in a couple of different ways.
This request to Copilot will use the selected code for the entire file as context
and target the tests to the scope provided in the prompt (see Figure 5.13).
Chapter 5 ■ Learning a New Programming Language 83
Figure 5.12: Successful run of unit tests via the dotnet test command
If you were to only select the Greeting method, the response from Copilot
would only use that information to consider the response. This would result in
a test that does not use the constructor that we implemented earlier.
After typing the #file tag, you should see a menu to select the file that you
want to reference. With this prompt, you should get a similar result to the
previous example using the selected text for the entire file.
Running Tests
Now that you have generated a baseline test for the Pirate.cs Greeting()
method, you can add this generated code to the test project. After adding this
file, you can run the dotnet test terminal command to initiate a new test (see
Figure 5.14).
In my case, I needed to add namespace to the Pirate.cs class on the first line
of the file for the generated unit tests to run.
namespace PiratesExample;
// greeting method
public string Greeting()
Chapter 5 ■ Learning a New Programming Language 85
{
return $"Ahoy! My name is {Name}, I am {Age} years old. I sail
on the {Ship}.";
}
Conclusion
This chapter provided a comprehensive guide on how to utilize GitHub Copilot
to learn a new programming language. Copilot’s ability to provide bespoke
insights and examples tailored to your interests and needs makes the process
of learning a new programming language less daunting and more engaging.
86 Part III ■ Practical Applications of GitHub Copilot
This chapter highlighted the flexibility and power of using Copilot in an IDE
like VS Code. Whether you’re exploring basic concepts, adding new code, or
learning through testing, Copilot serves as a valuable companion that acceler-
ates the learning curve and enriches the educational experience.
This practical application has shown you how Copilot can act as a mentor that
guides you through the intricacies of a new programming language, leveraging
your previous knowledge and adapting to your learning style. As you’ve seen
with the C# example, Copilot can provide personalized assistance every step
of the way, regardless of the programming language you choose to learn, from
setup to sophisticated coding practices.
Reference
[1] TIOBE, “TIOBE Index for February 2024,” 2024. [Online]. Available:
https://www.tiobe.com/tiobe-index
CHAPTER
87
88 Part III ■ Practical Applications of GitHub Copilot
The project example you will be using is a simple to-do application. In this
first section, you will be setting up the application programming interface (API)
for the project so that you can see how GitHub Copilot can facilitate creating
several different types of tests for a back-end API.
The API project used in this chapter is a NestJS API. This framework pro-
vides a robust testing suite and will enable us to cover several topics from unit
tests to integration tests and show how to leverage Copilot to assist write tests
along the way.
Prerequisites
To follow along with this example, you will need to install the following
prerequisites:
■■ Visual Studio Code:
https://code.visualstudio.com/download
■■ GitHub Copilot extension:
https://marketplace.visualstudio.com/items?itemName=
GitHub.copilot
■■ Node.js:
https://nodejs.org/en/download
■■ NestJS:
https://docs.nestjs.com/first-steps
■■ Jest extension:
https://marketplace.visualstudio.com/items?itemName=Orta
.vscode-jest
■■ Coverage Gutters extension:
https://marketplace.visualstudio.com/items?itemName=ryanluker
.vscode-coverage-gutters
After installing packages for the project, start the compilation mode watching
for changes and compiling when updates occur.
Chapter 6 ■ Writing Tests with Copilot 89
With the start script running, open a second terminal and run the following
command:
npm run test:watchAll
You will now have unit tests triggered on each change that will output cov-
erage results.
Lastly, if you would like to see inline test coverage results, run the coverage
gutters: watch process via the command palette or with the right-click menu
from any open editor.
After adding a new line under this comment, you will see a code completion
suggestion from Copilot (see Figure 6.1).
Given the context that you have provided Copilot, you should get a quality
starting point for the unit test that will cover the create() method in the
todo.controller.ts tab that is open adjacent to the test file. After running
this test, you will see that this does not match the expected result of the service
layer (see Figure 6.2).
If you had opened the todo.service.ts file before typing the inline com-
ment for the new test, Copilot would have created a test that aligns with the
existing code in the service. This service code currently returns a placeholder
string instead of an object type.
90 Part III ■ Practical Applications of GitHub Copilot
Later you will find that it will be necessary to modify this code to mock the
results from the service layer to remove the dependency on an external data-
base call.
Let’s add an isCompleted property to the service result object that you are
expecting in the unit test to round out what you would like to have returned
from the service function when creating a new to-do item (see Figure 6.3).
Now that you have a test case and object types that represent the desired result
from the service layer, let’s refactor the todo.service.ts file to align with this
unit test and get a passing test.
With the new properties added to the DTO and entity classes, let’s update
the create method to align with the expected result from the unit test. For this
update, you can utilize Copilot code completions to help guide you in typing
out the return object.
create(createTodoDto: CreateTodoDto): Todo {
return {
id: 1,
...createTodoDto,
isCompleted: false,
};
}
After you update the create() service function to align with the object type
properties specified earlier, you can then run the tests and you should see a
passing result (see Figure 6.4).
After you have the inline chat dialog open, you can use the /tests command
to indicate to Copilot that you would like tests created for the methods that are
selected in your file. Copilot will search for existing test class files that match
the naming convention of your file under test.
94 Part III ■ Practical Applications of GitHub Copilot
Copilot will allow you to review the changes that have been generated and
apply them if you choose to accept them. If you don’t like the tests Copilot
created, you can further guide the inline chat prompt to produce better results.
With the tests generated to your liking, you can head over to the todo
.service.spec.ts file. Here you will find the generated tests from your inline
chat request to Copilot. Remember, GitHub Copilot is nondeterministic and may
produce different results than the ones that I have. You should find a test that
covers each of your service file functions and validates the methods according
to their current parameters and response types (see Figure 6.6).
collaboration between the development team and product team members. BDD
testing is enabled by a requirements-writing language such as Gherkin. This
allows product team members to communicate clear expectations of a require-
ment to the development team and, as you will see in this section, help drive
the creation of tests that validate functionality. In our requirements examples,
you will be using the Gherkin syntax.
Setup
To begin, let’s first use the NestJS command-line interface (CLI) to add a new
resource to the codebase for your users. In a terminal window at the project
root, execute the following command:
nest g resource user
After choosing the REST API and clicking Yes to the CRUD entry points, you
should have a new resource added to the todo-api codebase (see Figure 6.7).
96 Part III ■ Practical Applications of GitHub Copilot
End-to-End Tests
Now that you have established a resource for your user feature, let’s look at
how you can use Copilot to assist you in writing your BDD tests.
End-to-end (E2E) tests are a great fit for BDD-style tests because they are
generally written from the perspective of user interaction with your system.
Thankfully, the NestJS framework assists you in generating these tests.
Scrolling down in the codebase, you will find a test folder at the root level of
your project. This has, by default, a test class for the main application entry point.
Let’s open the app.e2e-spec.ts class for context so that Copilot will know
how to assist you in writing the new tests (see Figure 6.8).
As specified in the package.json file, you can run these E2E tests with the
npm run test:e2e command in the terminal.
With the user.controller.ts and app.e2e-spec.ts files open, let’s add a new
class for our BDD tests. you can add this E2E test in the test folder and call it
user-creation.e2e-spec.ts. Within this file, you can then add the requirement
as a top-level comment to drive your test creation (see Figure 6.9).
Chapter 6 ■ Writing Tests with Copilot 97
With this top-level comment in place and our user.controller.ts and app
.e2e-spec.ts tabs open, you have a great context for Copilot to assist you in
completing your testing class.
Let’s add the same import statements as in the app.e2e-spec.ts file after the
comment to initialize Copilot’s code completion suggestion (see Figure 6.10).
Figure 6.10: User creation E2E test file with Copilot code Suggestion
After accepting the code from Copilot, ensure that it matches the desired
testing constraints and modify as needed. You can iterate on this process either
to refine the top-level comment or to add guiding code to steer Copilot into
providing you with the best possible code suggestions.
When you run these tests, you will find that your new tests fail due to the
specification you are coding not matching the existing API functionality (see
Figure 6.11).
With these tests, you can implement your new code with confidence. For
this example, you will stop short of doing the code refactors necessary for
this feature.
Chapter 6 ■ Writing Tests with Copilot 99
Figure 6.11: User creation E2E test file failing test run results
Conclusion
As you have seen in this chapter, GitHub Copilot can greatly enhance your
ability to write quality tests in a variety of situations. Whether you are writing
unit tests for existing code, integration testing a new system component, or
doing end-to-end testing on a vertical slice of your system functionality, Copilot
is there to help you create test suites that are more robust while allowing you
to stay in the flow of coding new features.
CHAPTER
In this chapter, you will take a closer look at how Copilot can help you diagnose
and resolve bugs. In these chapter examples, you will see a variety of circum-
stances that Copilot enables you to resolve coding issues without leaving your
development flow.
■■ Establishing the Example Project
■■ Fixing Syntax Errors
■■ Resolving Runtime Exceptions
101
102 Part III ■ Practical Applications of GitHub Copilot
Prerequisites
To follow along with this example, you will need to install the following
prerequisites:
■■ Visual Studio Code:
https://code.visualstudio.com/download
■■ GitHub Copilot extension:
https://marketplace.visualstudio.com/items?itemName=
GitHub.copilot
■■ Node.js:
https://nodejs.org/en/download
■■ NestJS:
https://docs.nestjs.com/first-steps
■■ Jest extension:
https://marketplace.visualstudio.com/items?itemName=Orta
.vscode-jest
■■ Coverage Gutters extension:
https://marketplace.visualstudio.com/items?itemName=ryanluker
.vscode-coverage-gutters
■■ ESLint:
https://marketplace.visualstudio.com/items?itemName=dbaeumer
.vscode-eslint
After installing packages for the project, start the compilation mode watching
for changes and compiling when updates occur:
npm run start:dev
With the start script running, open a second terminal and run the following
command:
npm run test:watchAll
You will now have unit tests triggered on each change that will output
coverage results.
Chapter 7 ■ Diagnosing and Resolving Bugs 103
Lastly, if you would like to see the inline test coverage results, run the
coverage gutters: watch process via the command palette or with the right-
click menu from any open editor.
Figure 7.1: Syntax error with highlighted code and error message
on the syntax error, in this case the “user” string, you can activate inline chat via
the keyboard shortcut or via the menu. After activating inline chat from with
your current position on the syntax error, Copilot will automatically input a
suggested prompt (see Figure 7.2).
In addition to pre-filling the prompt, after you submit your request to Copilot,
you will also see that Copilot provides an instruction of how to properly fix
this syntax issue.
If you are happy with the modified code that is previewed under the dialog,
you can accept the change and see the updated code according to Copilot’s
suggestion.
In this case, Copilot’s code suggestion would have been a reasonable way to
solve the compilation issue because it was an obvious fix. But in the case that
the error is not as obvious, it is nice to use inline chat to have a prepopulated
prompt and suggested fix directly in the editor to keep you moving.
As you will see, you still have some syntax errors that do not align to the
TypeScript rules. These are the data transfer objects (DTOs) you have defined
but never used. If you were to blindly accept Copilot’s suggestion here, you
would be taking a step backward away from the designed goal of creating and
updating new users (see Figure 7.3).
Chapter 7 ■ Diagnosing and Resolving Bugs 105
NOTE Always carefully review Copilot suggestions as they may not always align
with your desired outcome.
Setup
First let’s add username and password properties to the create-user.dto.ts
DTO class.
106 Part III ■ Practical Applications of GitHub Copilot
With those properties in place, you can add some basic functionality to the
user.service.ts class.
// Import Statements
@Injectable()
export class UserService {
users: User[] = [];
create(createUserDto: CreateUserDto) {
const { username, password } = createUserDto;
this.users.push(newUser);
return 'Account created';
}
// Remainder of Code
}
With this code established, let’s continue to add a unit test of this method
with a null DTO object. Open the user.service.spec.ts file and add a com-
ment to drive a test that will validate that the null reference scenario is handled
properly (see Figure 7.4).
// create null parameter throw BadRequestException
After generating this test, you will need to import the BadRequestExcpetion
class. Also, you will see that Copilot, in this case, suggests a deprecated function
called toThrowError versus the preferred toThrow. Because Copilot does not
receive real-time updates of packages and libraries, you may receive responses
that need to be adjusted like this example has highlighted.
With those adjustments in place, you can now run this test and observe the
function’s behavior when receiving a null parameter. You will see that the
test has failed with a TypeError thrown instead of the expected BadRequest
Exception (see Figure 7.5).
Chapter 7 ■ Diagnosing and Resolving Bugs 107
Figure 7.4: Inline comment for null parameter create method test
To initialize your unit test session, if you haven’t already, you can run the
following command:
npm run test:watchAll
You can now open the user.service.ts file and add the necessary code to
throw BadRequestException when you receive a null parameter in the user
service function.
When you add a new line after the create method signature, you will likely
get a code suggestion from Copilot to add a guard statement against the null
parameter (see Figure 7.6). This is due to the context that Copilot has with the
adjacent test file tab open.
Figure 7.6: User service create method guard statement code suggestion
If you don’t get a good suggestion from Copilot when adding a new line, you
can try typing out the first part of the if statement or adding an import for the
BadRequestException at the top of the file first.
After you accept this code from Copilot, you can save the file. With the guard
statement in place, the null reference test should pass (see Figure 7.7).
Chapter 7 ■ Diagnosing and Resolving Bugs 109
Figure 7.7: User service create method passing test for null reference exception
With this prompt, Copilot was able to determine that you have attempted to
check out a branch that doesn’t exist and provide you with a bespoke command-
line statement with the appropriate flag to create and check out the branch at
the same time.
Conclusion
In this chapter, you saw how GitHub Copilot can assist you with the complex-
ities of resolving syntax errors, smoothing over runtime exceptions, and over-
coming terminal errors. Interacting with Copilot has enabled you to transform
the debugging process from an isolated solo endeavor to a collaborative pair-
programming debugging session.
As you move forward with the knowledge from this chapter, look for ways,
unique to your codebase, that Copilot can assist you in having more bug-free
days and clean builds!
CHAPTER
In this chapter, you will learn how to use Copilot as a refactoring pair-
programming assistant. While code refactoring tools such as VS Code language
services and JetBrains ReSharper help you make safe refactors for your code,
you can use Copilot as a pair programmer in your refactoring efforts. Copilot
can assist you in exploring better ways to write your code and even assist you
when making changes. You can download a copy of the starter project todo-
api-ch08-starter in the Chapter 8 folder.
www.wiley.com/go/programminggithubcopilot
■■ Refactoring Validators
113
114 Part III ■ Practical Applications of GitHub Copilot
a test suite that covers your code to ensure that you do not modify your
external behavior.
The goal in code refactoring is to increase the maintainability of your code
and enhance its extensibility. Maintainable code is easy to understand, navi-
gate, and modify. Extensible code is flexible and adaptable to the needs of your
application as it advances over time.
You have seen how Copilot can assist you in creating new tests, functions,
classes, and even entire program templates. We have not yet explored how
Copilot can assist you in code refactoring. Traditionally, refactoring tools have
been defined as tools that understand the parse tree of your application and
are able to make precise modifications to your files. As we have discussed
in this book, Copilot is founded on large language models that allow it to
predict the next most likely token given the context that you have provided.
Copilot interacts with your code more similarly to how you would edit code
via text updates.
When using Copilot to assist you in code refactoring, you should not attempt
to replace the existing integrated development environment (IDE) IDE tooling
that helps with precise refactors such as function extraction and formatting tools.
While Copilot is capable of assisting in a variety of refactoring tasks, it is just as
important to ensure that you are choosing the right tool for the right job when it
comes to code refactoring. Copilot is here to help guide you through refactoring
code even if you use other tools to do the refactoring. You can bounce ideas off
Copilot for better solutions to your code organization, learn how you can reduce
the complexity of functions, explore best practices in design patterns, and more.
Prerequisites
To follow along with this example, you will need to install the following
prerequisites:
npm install
After installing the packages for the project, start the compilation mode
watching for changes and compiling when the updates occur.
After this, you can open a second integrated terminal and run the following
command:
You will now have unit tests triggered on each change that will output cov-
erage results. You will continue using the VS Code extension Coverage Gutters.
This extension uses the coverage output to show you which lines of code have
been covered by the unit tests.
You can activate the “coverage gutters: watch” process via the command
palette or via the right-click menu from any open editor.
When running the npm run test:watchAll command in the terminal, you
may notice the NestJS error logs. Those are from the unit tests that are covering
the logger.error() statements within the user.controller.ts class.
116 Part III ■ Practical Applications of GitHub Copilot
In the update() function, you will see that you have the same logging code
as you have in the findOne() function. This code is duplicated in each of the
functions.
As mentioned at the beginning of this chapter, it is important to use IDE tool-
ing for precise refactoring when possible. And, you must always have a solid
test suite before you can refactor due to the risk of potentially breaking your
external behavior with internal code changes.
Chapter 8 ■ Code Refactoring with Copilot 117
The first step in your refactoring efforts in this controller will be to ensure that
you have the external behaviors covered by your test suite. You can see from
the previous figure that you have coverage on your findOne() method but not
on the update() function. Let’s see how Copilot can assist you in covering this
function with unit tests to allow you to refactor with confidence.
Figure 8.2: User controller test file with code completion for the update function
118 Part III ■ Practical Applications of GitHub Copilot
like to create tests for, then activate inline chat via the keyboard shortcut or the
right-click menu. With the inline chat dialog active, type /tests in the dialog
input (see Figure 8.3).
After you send the tests prompt to Copilot, you will get a refactor preview
window that allows you to review the changes that Copilot has made to your
code and apply or discard them (see Figure 8.4).
Copilot has found that you have a user.controller.spec.ts file that covers
the class that your remove() function is in. You can view the proposed refactor
in detail by double-clicking the result and viewing the code.
After accepting this code, you may need to clean up the output due to the way
the code was populated in the test file. From my experimentation, inline chat
test creation does better when there are no existing tests in the corresponding
test file. When tests do exist, you need to clean up the output slightly to get it to
adhere to your class structure. This will most likely be altered in future updates,
allowing for a more seamless code refactoring activity.
In this example, you will see Copilot reference “existing code” in a comment
while not making the adjustment to my code file with the new code placed in
the correct location (see Figure 8.5).
Chapter 8 ■ Code Refactoring with Copilot 119
Figure 8.4: User controller inline chat tests prompt refactor preview window
Figure 8.5: User controller tests remove function result from inline chat tests command
120 Part III ■ Practical Applications of GitHub Copilot
With the new test added, I will cut the remove describe() function and
paste it within the existing describe() function for the UserController and
remove the duplicate describe() function for the UserController on line 148.
(see Figure 8.6).
Figure 8.6: User controller tests file with adjustment from inline chat result
After submitting this request to Copilot, you should see a response indicating
the proposed refactor along with an explanation of why Copilot feels this is a
valid adjustment to your code (see Figure 8.8).
Chapter 8 ■ Code Refactoring with Copilot 121
Figure 8.7: User controller code selected with inline chat prompt for refactor
After accepting this code, you can save the file to initialize your unit test run.
You should see that you are still getting the same external behavior with your
simplified controller error logging.
While there are many ways to log in to an API, this is just a simple example of
how you can leverage Copilot to help you reduce your code while maintaining
the expected behavior. In some cases, IDE refactoring tools such as the extract
function could be a great solution. But when appropriate, as shown here, Copilot
can help you adjust your code quickly and accurately.
Refactoring Validators
Validation logic starts simple in a lot of projects but can quickly outgrow its
container functions, causing increased complexity and reduced maintainability
of the code.
The next focus area will be in the user.service.ts file. Here you have a
create() method that has validation code for the username and password fields.
While it is good to add guard clauses and validation for the user-provided input,
placing large quantities of code with varied responsibilities in a single function
will cause decreased maintainability. Let’s explore how you can add tests and
refactor this code with Copilot.
Figure 8.9: User service create method validation code with tests prompt
Using this extract selected code tooling, continue to refactor the create()
method. Extract the parameter validation to a function, extract the bcrypt hash
password to a function, and finally extract the duplicate entry error code to a
function. With these changes you should see a resulting create() method that
is much more maintainable (see Figure 8.13).
While in this case you used built-in refactoring tools for the specific task of
extracting code to functions, Copilot can assist you in going further and explore
what more you could do that you might not have the knowledge of or have
thought of on your own.
Let’s open a chat with Copilot and see what other considerations you should
make when refactoring validation code in your service functions. With a prompt
like the following, you should get a detailed response from Copilot indicating
some additional steps you can take and get example code bespoke to your
model (see Figure 8.14):
What refactors would you suggest for the validation code in my service?
Should I consider using a different approach? #file:user.service.ts
NOTE When using the #file variable within the Copilot chat, you must use the
drop-down menu to select the file.
126 Part III ■ Practical Applications of GitHub Copilot
Figure 8.13: User service create method extended code refactoring result
Figure 8.14: Copilot chat response to additional refactoring that could be done for validation code
Chapter 8 ■ Code Refactoring with Copilot 127
Use Middleware for Validation: You can use middleware to validate the request
data before it reaches your service methods. This way, your service methods will
only run if the request data is valid.
Use Decorators for Validation: In NestJS, you can use decorators like @IsString(),
@IsNotEmpty(), @Length(), etc., from the class-validator package in your DTOs.
This will automatically validate the incoming request data based on the decorators
you’ve used.
Separate Validation to a Different Method or Class: If you don’t want to use
middleware or decorators, you can at least separate the validation code to a differ-
ent method or even a different class. This will make your service methods cleaner
and easier to read.
Use a Validation Library: There are many validation libraries available for TypeScript/
JavaScript like Joi, Yup, etc. These libraries provide a declarative way to define
validation rules and can make your validation code cleaner and easier to manage.
Interacting with Copilot to plan your refactoring techniques and get action-
able results is a powerful tool. In this example, you can explore a variety of code
refactoring options and choose the right solution for your needs.
After submitting this request to Copilot, you will receive an inline refactor
with an explanation of the suggested refactor (see Figure 8.16).
128 Part III ■ Practical Applications of GitHub Copilot
Figure 8.15: Copilot inline chat refactor bad variable names prompt
Figure 8.16: Copilot inline chat refactor bad variable names refactor result
Chapter 8 ■ Code Refactoring with Copilot 129
There are many ways to accomplish renaming refactors in your code. When
renaming variables, Copilot works best when targeting single-file updates.
When you start to modify code that might have external dependencies, using
our IDE-based tooling can ensure the reactor is accounting for the external file
references and adjusting those files as well.
Method Documentation
Let’s explore how Copilot can assist you in documenting your code. With your user
.service.ts file open, you can select all the lines in the class and activate Copilot
inline chat. With the chat active, you can use the /doc command to give Copilot the
context of your intent and assist you in a more accurate refactor (see Figure 8.17).
Figure 8.17: Copilot inline chat add documentation to user service class
130 Part III ■ Practical Applications of GitHub Copilot
After submitting this request to Copilot, you should get a response with the
method descriptions for all the methods in the UserService class. You will see
that you have seven changes you can cycle through and choose to accept or
discard those suggested documentation blocks (see Figure 8.18).
Figure 8.18: Copilot inline chat add documentation to user service class result
This initial response from Copilot was great. Always review each of the
modifications that Copilot provides and ensure they match the functionality.
You can now benefit from these documented methods and better understand
the inputs, outputs, and expected behavior (see Figure 8.19).
Project Documentation
With all the hard work you have put into your project, you need to make sure
you document the overall project and allow other contributors to understand
your project structure and features.
You will use Copilot chat to create a baseline readme.md file for the todo-api
project. Opening the Copilot chat window, you can add the following command
to get Copilot to generate documentation for you:
@workspace Please write a readme for my todo-
api project.
After you submit this request to Copilot, you should get a result with bespoke
details for your project (see Figure 8.20).
Chapter 8 ■ Code Refactoring with Copilot 131
Figure 8.20: Copilot chat response to generate the project README.md file
132 Part III ■ Practical Applications of GitHub Copilot
Here you can see that Copilot used six files from the codebase and cre-
ated a great starting point for you to have a useful and detailed descriptive
README.md file.
From my testing, it seems the best way to get the generated markdown for
the Copilot response is to right-click the response area and click Copy. This will
allow you to paste the markdown in your project README.md file.
Conclusion
This chapter touched on the history of refactoring code, the tools and tech-
niques used today, and how you should best incorporate Copilot into your
code refactoring workflow.
You looked at examples from a project that showcased Copilot’s ability to
assist you in creating a test suite to enable confident refactoring of code.
After establishing some tests, you explored how Copilot was able to assist in
a variety of refactoring tasks, from duplicate code reduction to documentation.
Through these examples, I hope you have seen how Copilot can be an asset to
you as you refactor your codebases.
CHAPTER
In this chapter, you will be equipped with the ability to fully utilize GitHub
Copilot to assist you in enhancing your code security. This chapter will out-
line the importance of security, how Copilot can assist you in learning about
security vulnerabilities and best practices, and ways to apply that knowledge
to your codebase to make corrective measures before releasing insecure code
to your users.
■■ Detailing Code Security
■■ Establishing the Example Project
■■ Exploring Code Security
133
134 Part III ■ Practical Applications of GitHub Copilot
vulnerabilities that exist in software applications today. OWASP, which has existed
since 2001, is well-known for its top 10 application security vulnerability lists.
https://owasp.org/Top10
The OWASP top 10 list is a great start for teams to understand the most
prominent security threats facing the software industry. While this information
empowers developers to make changes to their code, it is important to imple-
ment a multifaceted security suite to protect against security threats.
With the increasing complexity of modern web applications and the steady
rise in security threats, application security has become a critical part in the
software development life cycle (SDLC). The need for enhanced applica-
tion security gave rise to the term application security development operations
(DevSecOps). Traditional security practices often struggle to keep up, leading
to vulnerabilities being discovered late in the process or even after deploy-
ment, when they are costly and disruptive to fix. DevSecOps addresses this
by integrating security practices directly into the SDLC. This “shift left”
approach ensures that security is considered at every stage of development,
from initial design through deployment and maintenance. Automated test-
ing, continuous monitoring, and proactive threat modeling become integral
parts of the process, enabling teams to catch and fix issues early when they
are easier to manage.
In this chapter, you will learn how GitHub Copilot can be used to assist in
producing secure code. This chapter will also detail how Copilot can be used
to help you learn about security best practices and vulnerabilities specific to
your codebase.
Prerequisites
To follow along with this example, you will need the following prerequisites
installed:
■■ Visual Studio Code
https://code.visualstudio.com/download
■■ GitHub Copilot extension
https://marketplace.visualstudio.com/items?itemName=GitHub
.copilot
■■ Node.js
https://nodejs.org/en/download
■■ NestJS
https://docs.nestjs.com/first-steps
■■ Jest extension
https://marketplace.visualstudio.com/items?itemName=Orta
.vscode-jest
■■ ESLint
https://marketplace.visualstudio.com/items?itemName=dbaeumer
.vscode-eslint
After installing packages for the project, start the compilation mode watching
for changes and compiling when updates occur:
npm run start:dev
After this, you can open a second integrated terminal and run the following
command:
npm run test:watch
Figure 9.1: Copilot Chat response for best practices for NestJS APIs
You will see Copilot respond with a set of targeted security practices that
would be a great start for a security audit of the application. The following are
the security practices that Copilot suggested as best practices:
1. Use HTTPS: Always use HTTPS for secure communication. This ensures
that the data transferred between your server and the client is encrypted and
cannot be intercepted.
2. Validation: Use class-validator and class-transformer packages to validate
incoming requests.
3. Error Handling: Don’t expose sensitive error details to the client. Use a global
exception filter to catch and handle errors.
4. Rate Limiting: Implement rate limiting to protect your APIs from brute force
and denial of service attacks.
5. Use Middleware for Authentication: Use Passport.js, a popular middleware for
Node.js, for managing user authentication.
6. Use Guards for Authorization: Use NestJS Guards to manage user roles and
permissions.
Chapter 9 ■ Enhancing Code Security 137
7. Use Helmet: Helmet can help protect your app from some well-known web
vulnerabilities by setting HTTP headers appropriately.
8. Use CSRF Protection: If you’re serving HTML with your NestJS server, you’ll
need CSRF protection. You can use the csurf middleware for this.
9. Update Dependencies: Regularly update your project dependencies to get the
latest security patches.
10. Use Environment Variables for Sensitive Data: Never hard-code sensitive data.
Use environment variables instead.
Let’s examine how you can take the conversation further to get actionable
suggestions for some of these security controls.
Using HTTPS
Continuing the conversation, ask Copilot the following:
How do I use HTTPS in a NestJS API?
With this request, Copilot will return detailed, step-by-step instructions for
you to produce a certificate for testing purposes and make the appropriate
modifications to the main.ts file of your application (see Figure 9.2).
Figure 9.2: Copilot Chat response for how to use HTTPS in a NestJS API
138 Part III ■ Practical Applications of GitHub Copilot
Implementing Validation
Up next, let’s see what Copilot suggests for validation. Ask Copilot the following:
How to do input validation in a NestJS API?
With this request, Copilot will return another detailed response with specific
instructions to implement this security control (see Figure 9.3).
Figure 9.3: Copilot Chat response for how to do input validation in a NestJS API
In this case, you can see that Copilot gives necessary package installations,
DTO object modifications, controller class update requirements, and instructions
for implementing a global pipeline validator.
Conclusion
As you can see from this example, with some basic questions about security,
you can navigate the complexities of securing a modern API. Make sure to
always verify the suggestions with Copilot if you are unsure of the sug-
gested result.
Chapter 9 ■ Enhancing Code Security 139
This request should give you a result indicating that the code has weak pass-
word hashing, potential SQL injection, error handling leaking sensitive data, lack
of rate limiting, no salting of password, and password validation enhancements
that are needed (see Figure 9.4).
Figure 9.4: Copilot Chat response for user service security issues
140 Part III ■ Practical Applications of GitHub Copilot
Now that you have these insights into security issues that may need to be
addressed, Copilot can continue to help as you navigate the modifications
required to fix the security issues found.
Figure 9.5: Copilot Chat response for how to fix weak password hashing
Copilot will provide the suggested package needed to enhance the hashing
algorithm. The response from Copilot should also contain the steps required
to implement security fix.
To implement the requested changes, run the following npm install command
for the bcrypt package:
npm install bcrypt
Now, instead of navigating around the file to adjust imports, you can uti-
lize Copilot inline chat to make the necessary adjustments to code. With the
hashPassword() function selected, activate the Copilot inline chat.
Chapter 9 ■ Enhancing Code Security 141
You can then provide a request to Copilot using the /fix command to resolve
the hashing refactor (see Figure 9.6).
/fix the hash password function to use bcrypt
Figure 9.6: Copilot Chat response for how to fix weak password hashing
After Copilot processes the request, you should see a preview of the suggested
refactors and an explanation for the adjustments that have been applied. In this
case, two changes are provided. One change is for the function doing the pass-
word hashing, and the other change is to add the import for the bcrypt library.
NOTE When adjusting existing code with the Copilot inline chat, using the /fix
command will be better suited to make multiple adjustments in the current file.
Within this response, you can see that Copilot identified that the findOne
method had a potential SQL injection issue. After navigating to this code within
the user.service.ts file, you will see that there is a query accepting a username
parameter without being properly sanitized.
To fix this issue, Copilot inline chat is a great option. Select the username query
inside the findOne method in the editor window. After making that selection,
activate inline chat. You can then provide a request to Copilot like in Figure 9.7.
Figure 9.7: Copilot Chat response for how to fix SQL injection
Conclusion
In this chapter, Copilot proved to be a powerful asset in the software development
lifecycle when confronting security issues. Through practical application within
the example project, you saw how Copilot not only identifies vulnerabilities
but also guides the implementation of robust security measures. As you move
forward, let the insights gained here inspire a deeper integration of Copilot into
your security practices.
CHAPTER
10
In this chapter, you will learn how Copilot can assist in several DevSecOps tasks.
DevSecOps tasks can be complicated to learn and implement. With Copilot by
your side, you will be empowered to create the necessary resources and actions
that will get your application from concept to center stage.
■■ Detailing DevSecOps
■■ Simplifying Containers
■■ Automating Infrastructure as Code
Detailing DevSecOps
DevSecOps, short for development, security, and operations, is a software engi-
neering culture and practice that aims to unify software development (Dev),
security (Sec), and operations (Ops).
To practice DevSecOps, security needs to be considered at every phase of the
software development life cycle (SDLC) (see Figure 10.1).
As you can see from Figure 10.1, in addition to the development tasks, the
release, deployment, operation, and monitoring tasks all play a vital role in
successful software delivery with security embedded at every task.
143
144 Part III ■ Practical Applications of GitHub Copilot
Sec
CODE DEPLOY
PL
AN
Dev Ops
OPERATE
AS
B UIL D
LE
RE
M
ON
TEST IT O R
Figure 10.1: DevSecOps diagram detailing security considered at each stage of the DevOps cycle
Simplifying Containers
A container is a lightweight, stand-alone, and executable software package that
includes everything needed to run a piece of software. This includes the code,
a runtime, libraries, environment variables, and config files.
Chapter 10 ■ Accelerating DevSecOps Practices 145
In this section, you will see how Copilot can assist in writing container con-
figuration files and support running the application within a container.
Creating a Container
Let’s explore how Copilot can assist in creating a container to run a NestJS
API. To showcase this capability, open a Copilot Chat window. After you have
that open, you can enter a prompt to request help to create a container.
Request to Copilot (see Figure 10.2):
Help me create a production container for my NestJS API project.
Figure 10.2: Copilot Chat response for how to create a container for a NestJS API
You will see Copilot respond with a Dockerfile and instructions on how to
build and run the image.
Within this resulting Dockerfile, Copilot suggests the use of Node.js version
14. GitHub Copilot is trained on a large dataset of publicly available code, but
it doesn’t know specifics about which libraries or versions it was trained on.
The base functionality of Copilot doesn’t have the ability to access or retrieve
information beyond its training data. With this functionality in mind, it is always
146 Part III ■ Practical Applications of GitHub Copilot
important to ensure the version numbers and syntax match the current versions
and syntax is matched to the needs you have. You can add context to Copilot
with example files of current standards or library versions to get a generated
output that aligns better with your needs.
Here is the Docker file that Copilot returned:
# Define the base image
FROM node:14
# Install dependencies
RUN npm install
Deploying a Container
Copilot has provided a great follow-up prompt given the initial question about a
container for an API project. If you did not receive this prompt, you can submit
the following to see how you could deploy a container to a cloud platform (see
Figure 10.3).
Insert your cloud platform of choice to receive detailed instructions targeted
to your specific needs.
Chapter 10 ■ Accelerating DevSecOps Practices 147
Figure 10.3: Copilot Chat response for how to deploy a Dockerized NestJS API to a cloud
platform
Figure 10.4: Copilot Chat response for what security controls can be applied to a Dockerized
NestJS API
Creating IaC
Starting with a basic request to Copilot, you can get a detailed outline and starter
implementation for your application (see Figure 10.5).
Here is the request to Copilot:
Help me create a infrastructure as code for my NestJS API project.
Chapter 10 ■ Accelerating DevSecOps Practices 149
Figure 10.5: Copilot Chat response for what security controls can be applied to a Dockerized
NestJS API
You will see Copilot respond with a detailed step-by-step plan to create your
IaC using Terraform. Copilot should also suggest a basic example of a main.tf
file that will provision the resources required for a NestJS API (see Figure 10.6).
Here is the Terraform file:
provider "aws" {
region = "us-
west-
2"
}
tags = {
Name = "nestjs_api"
}
}
ingress {
from_port = 3000
to_port = 3000
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-
1"
cidr_blocks = ["0.0.0.0/0"]
}
}
Figure 10.6: Copilot Chat response for how to deploy NestJS API using Terraform
configuration files
Chapter 10 ■ Accelerating DevSecOps Practices 151
container_definitions = <<DEFINITION
[
{
"name": "nestjs-
container",
"image": "<your-
dockerhub-
username>/nestjs-
api",
"essential": true,
"portMappings": [
{
"containerPort": 3000,
"hostPort": 3000
}
]
}
]
DEFINITION
}
Figure 10.7: Copilot Chat response for what security controls should be added for this deploy-
ment process with Terraform
The result from Copilot helps guide you to critical security measures, such
as securing AWS credentials, least privilege principle, securing Docker images,
and more.
code changes or pull requests are submitted to the repository, the submitted
code is built, tested, and scanned for security vulnerabilities and code smells.
Continuous delivery is the practice of automating the entire software release
process. With CD, you can deploy to production at any time. This ability enables
you to release an updated version of your application code to any environment
with automated triggers or release gates to ensure control for sensitive envi-
ronments is maintained.
Creating CI Pipeline
Starting with continuous integration to the source code repository, you will see
how Copilot can support the creation of automated tasks that allow for quality
contributions to your application codebase (see Figure 10.8).
Here is the request to Copilot:
Help me create a continuous integration pipeline for my NestJS API
project dev branch and pull request.
Figure 10.8: Copilot Chat response for help creating a continuous integration pipeline
This result from Copilot provides a good starting point for a GitHub Actions–
based CI pipeline that will support listening for changes to your repository
154 Part III ■ Practical Applications of GitHub Copilot
branch of choice, building the application, and running any tests that the
application has.
Here is the GitHub workflow .yml file:
name: CI
on:
push:
branches: [ dev ]
pull_request:
branches: [ dev ]
jobs:
build:
runs-
on: ubuntu-
latest
strategy:
matrix:
node-version: [12.x]
steps:
-uses: actions/checkout@v2
-name: Use Node.js ${{ matrix.node-
version }}
uses: actions/setup-
node@v2
with:
node-
version: ${{ matrix.node-
version }}
-run: npm ci
-run: npm run build -
-i
f-
present
-run: npm test
Like previous responses from Copilot, the Node.js version is not reflective
of what would work for a modern NestJS API project today. So, as always,
remember to review the output provided by Copilot for accuracy to the needs
of your project.
Figure 10.9: Copilot Chat response for help creating security scanning for a continuous
integration pipeline
Copilot has responded with a great suggestion to include the GitHub Cod-
eQL library. CodeQL is a semantic code analysis engine enabling the GitHub
action github/codeql-action/analyze to run a series of queries against your
code and report any security issues it has found. CodeQL is open-source, and
the security findings that it reports are supported by the community of security
experts continuing to expand the ability of the library as the security landscape
changes year after year.
While the CodeQL library queries are open-source, the underlying engine is
not licensed for commercial use. To use CodeQL in a commercial setting, you
need to use GitHub Advanced Security.
Here is the updated GitHub workflow .yml file:
name: CI
on:
push:
branches: [ dev ]
pull_request:
156 Part III ■ Practical Applications of GitHub Copilot
branches: [ dev ]
jobs:
build:
runs-
on: ubuntu-
latest
strategy:
matrix:
node-version: [12.x]
steps:
-uses: actions/checkout@v2
-name: Use Node.js ${{ matrix.node-
version }}
uses: actions/setup-
node@v2
with:
node-
version: ${{ matrix.node-
version }}
-run: npm ci
-run: npm run build -
-i
f-
present
-run: npm test
codeql:
name: Run CodeQL
runs-on: ubuntu-
latest
steps:
-name: Checkout repository
uses: actions/checkout@v2
Creating CD Pipeline
Now that you have a CI GitHub Action established, the next thing needed is
to release changes to environments for functional testing, pen testing, staging
validation, and production delivery.
Create a new conversation with Copilot in a chat window and ask the fol-
lowing (see Figure 10.10):
Help me create a continuous deployment GitHub Action for my NestJS API
project dev branch merges. Create a Docker image, store the image, tag
it, and release to a development AWS EC2 environment.
Chapter 10 ■ Accelerating DevSecOps Practices 157
Figure 10.10: Copilot Chat response for help creating a continuous deployment action
This response from Copilot has detailed all the necessary steps in a GitHub
Action that would enable your code to be built, published, and deployed.
Here is the CD workflow .yml file:
name: CD
on:
push:
branches:
-dev
jobs:
build:
runs-
on: ubuntu-
latest
steps:
-name: Checkout code
uses: actions/checkout@v2
deploy:
needs: build
runs-on: ubuntu-
latest
steps:
-name: executing remote ssh commands to deploy
uses: appleboy/ssh- action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.SSH_KEY }}
script: |
docker pull your-dockerhub-
username/your-
repo-
name:latest
docker stop api-container || true
docker rm api-container || true
docker run -d -
-
name api-
container -
p 80:3000 your-
dockerhub-
username/your-repo-name:latest
This continuous delivery workflow file is a great start for you finalizing the
CI/CD process for a dev branch. Always remember to review and test code and
scripts provided by Copilot.
Conclusion
In this chapter, you saw how Copilot can be a great asset in the DevSecOps pro-
cess, enabling you to do more and stay in the flow. Even with complicated tasks
like infrastructure as code and security scanning in a DevOps pipeline, Copilot
has your back and will always be ready to support you in your DevSecOps
activities.
CHAPTER
11
Enhancing Development
Environments with Copilot
In this chapter, you will discover how Copilot can assist you in a multitude
of development environments. Whether you are running a command in the
terminal or creating an enterprise application in Visual Studio, Copilot has you
covered. Let’s explore how you can get the most out of your IDE and enhance
your development workflow with Copilot.
■■ Amplifying Visual Studio with Copilot
■■ Elevating Azure Data Studio with Copilot
■■ Boosting JetBrains IntelliJ IDEA with Copilot
159
160 Part III ■ Practical Applications of GitHub Copilot
While there are many different technologies that can be used in Visual Studio,
using .NET in Visual Studio is where it really shines. .NET is an open-source,
cross-platform framework for building modern apps and cloud services.
Prerequisites
■■ GitHub Copilot license
https://github.com/features/copilot
■■ Window OS
https://www.microsoft.com/software-download/windows11
■■ Visual Studio
https://visualstudio.microsoft.com/downloads
For both the GitHub Copilot and GitHub Copilot Chat extensions, select
Download. You will now be notified at the bottom of the extensions window
Chapter 11 ■ Enhancing Development Environments with Copilot 161
that the changes will be scheduled, and modifications will begin when all Visual
Studio windows are closed. Proceed to close all Visual Studio windows.
After closing Visual Studio, you will be prompted with a VSIX Installer window
that will complete the installation of GitHub Copilot and GitHub Copilot Chat
(see Figure 11.2).
After completing the installation, open Visual Studio. When you have loaded
the IDE, open the Accounts menu at the top right of the screen. From there, if
you haven’t already, add your GitHub account via the Add Another Account
menu (see Figure 11.3).
After following the steps to authenticate with GitHub, you should now be
set up to use GitHub Copilot in Visual Studio.
As you start writing this comment, Copilot should start suggesting some text
to complete it (see Figure 11.4).
After completing the top-level comment, add a second line to indicate the
valid examples to help Copilot to provide the best result possible.
// valid examples: racecar, taco cat
Chapter 11 ■ Enhancing Development Environments with Copilot 163
With those comments now in place, enter two new lines to get another sug-
gestion from Copilot. Within Visual Studio, you can also trigger a code com-
pletion via the keyboard shortcut. For more information on keyboard shortcuts
and configuration of your Visuals Studio environment, check out the official
documentation at the following URL:
https://docs.github.com/copilot/configuring-github-copilot/
configuring-github-copilot-in-your-environment?tool=visualstudio
Copilot will most likely suggest the statement using System;. After accepting
that line, add another two lines to the file and wait for another code completion
suggestion from Copilot. You should see Copilot attempting to complete a console
program that has user input and checks if the input is a palindrome (see Figure 11.5).
After accepting this suggestion from Copilot, you can inspect the generated
code and run the application to test.
After opening the chat view, you should see the ability to send a message to
Copilot to start the conversation. Copilot Chat in Visual Studio supports slash
commands for targeted context to assist Copilot in giving a great result. Visual
Studio also supports tags that allow for targeted context for Copilot to know
which files should be considered when giving you a response (see Figure 11.6).
GitHub Copilot Chat for Visual Studio does not currently have support for
agents such as @workspace, @terminal, and @vscode. While the @workspace can
be useful to automatically gain appropriate context for your prompt, you can
achieve a similar effect by using multiple tagged files with #file in a prompt to
allow for Copilot to have enough information to make a response that should
consider many files within your project.
While agents are not present, you can trigger inline chat with Copilot right
within your editor. You can right-click within the editor to trigger inline chat
via the menu. Also, the preferred way is using the keyboard shortcut (Alt+/)
(see Figure 11.7).
In this case, you can see inline chat in action by selecting the IsPalindrome
function and activating inline chat. Select the /doc command. After selecting
/doc, submit the request to Copilot. You should get a response with an inline
code diff allowing you to review the changes made to the code and accept or
cancel them (see Figure 11.8).
Chapter 11 ■ Enhancing Development Environments with Copilot 165
Prerequisites
■■ GitHub Copilot license
https://github.com/features/copilot
■■ Azure Data Studio
https://azure.microsoft.com/products/data-studio
After that line, add another indicating some more instruction to Copilot to
assist in query completion.
-
-Create a database schema for a SQL Server database that will store
the following data:
After adding this line, add a new comment. In my case, Copilot quickly sug-
gested a line indicating the database would store information about customers.
Continue the new line comment creation until you have a few tables like this
top-level comment:
-
-SQL Server Database Schema
-
-Create a database schema for a SQL Server database that will store
the following data:
-
-1. A table to store information about customers. Each customer has a
unique ID, a name, and an email address.
-
-2. A table to store information about products. Each product has a
unique ID, a name, and a price.
-
-3. A table to store information about orders. Each order has a unique
ID, a customer ID (from the customers table), a product ID (from the
products table), and a quantity.
With this comment in place, you can now proceed down two new lines and
lead Copilot to initiate the database schema creation if it doesn’t already start.
-
-Create the customers table
With this comment, add a new line and then wait for a CREATE statement to
be created. Repeat this new line process to the bottom of the file until you have
three tables created for customers, products, and orders (see Figure 11.11).
-
-Insert some sample data into the customers table
Copilot will assist in writing the test data but will make you provide emails
to ensure that it is not injecting any predicted emails that would be realistic.
After finishing two records of customer data, finishing that statement, and
moving to another line, Copilot will assist with insert new test data. Add sample
data for the remaining products and orders table (see Figure 11.12).
Chapter 11 ■ Enhancing Development Environments with Copilot 169
After completing this comment, Copilot will again jump in to help you complete
the SQL query you are wanting to write (see Figure 11.13).
This example of GitHub Copilot within Azure Data Studio highlights the
impressive skillset and how Copilot can assist in creating database schemas,
constructing test data, and formulating complex queries.
Giving Copilot quality context is essential to the success of receiving quality
responses. You can accomplish similar tasks in other IDEs. And by using skills
like file tagging to reference database schema files, you can create queries
in separate files and allow Copilot to access your database schema via a file
reference.
Chapter 11 ■ Enhancing Development Environments with Copilot 171
Prerequisites
■■ GitHub Copilot license
https://github.com/features/copilot
■■ JetBrains IntelliJ IDEA
https://www.jetbrains.com/idea/download
search for GitHub Copilot. From here, select the search result and click Install
(see Figure 11.14).
Figure 11.14: IntelliJ IDEA plugins search result screen with GitHub Copilot
After installing GitHub Copilot, you will be prompted to restart the IDE. Restart
the IDE; after doing this, click New Project from the welcome page.
To see how Copilot can work within IntelliJ IDEA, let’s create a Palindrome
Checker Java project (see Figure 11.15).
After creating the project, you should see a prompt to sign in to GitHub
at the bottom right. If you don’t see this pop-up, you can also sign in via the
welcome screen to the GitHub Copilot window accessible in the left menu (see
Figure 11.16).
From this window or the Copilot icon on the bottom-right menu, sign in to
your GitHub account using the steps outlined by the authentication prompt.
After completing the top-level comment, add a second line to indicate valid
examples to help Copilot provide the best result possible.
// valid examples: racecar, taco cat
With those comments now in place, enter two new lines to get another sug-
gestion from Copilot. Copilot will most likely suggest an import statement:
import java.util.Scanner;. After accepting that line, add another two lines
and wait for another code completion suggestion from Copilot. You should
see Copilot attempting to complete a console program that has user input and
checks if the input is a palindrome (see Figure 11.17).
After accepting this suggestion from Copilot, you can inspect the generated
code and run the application to test.
In my case, the resulting isPalindrome function did not include a state-
ment to remove spaces and convert to lowercase like the C# example did.
Chapter 11 ■ Enhancing Development Environments with Copilot 175
To resolve this issue, add a comment to the isPalindrome function before the
loop as follows:
// remove spaces and convert to lowercase
With this comment in place, add a new line and wait for Copilot to provide a
code suggestion. After you accept the next line, you can run the application and
test that the valid examples are returning the correct value (see Figure 11.18).
Within the chat result, you can use the Insert Code Block At Cursor button
at the top right of the generated code block in the response from Copilot. After
doing this, the updated isPalindrome function with full documentation will
be inserted into the editor.
Currently, inline chat is not supported in IntelliJ IDEA. But as you have seen,
working with Copilot Chat in the windowed experience and transferring results
to your editor is a breeze.
Prerequisites
■■ GitHub Copilot license
https://github.com/features/copilot
■■ Neovim
https://neovim.io
■■ Node.js
https://nodejs.org/en/download
Start Neovim via the nvim command and run the following command:
:Copilot setup
After logging in to your GitHub account, you are now ready to enable Copilot.
Run the following command to enable Copilot:
:Copilot enable
Open the dad-jokes.js file with Neovim with the following command:
nvim dad-jokes.js
After opening the file, Copilot should be enabled from the installation steps,
so you can proceed to adding a top-level comment to the file. To start editing
the file, press the i key to activate “insert” mode. Start by typing the following:
// Node.js script that fetches a random dad joke from the
icanhazdadjoke API
You will notice that Copilot, using the context of the filename, already com-
pletes the ending of the comment (see Figure 11.20). You can accept the request
by hitting the Tab key.
After you have added the second comment, add two blank lines to the file.
You should then be prompted with a code suggestion with the https variable
declaration. Accept that line, and then add two more blank lines. Copilot should
suggest a comment or function for fetching the dad joke (see Figure 11.21).
After accepting the fetchDadJoke()function, add two more blank lines and
make a call to the fetchDadJoke() function. After you are done, your file should
look like Figure 11.22.
With the export in place, hit the Esc key to stop editing. Now, save and quit
the file via the :wq command.
After you are back in the terminal, run the following command to test the
function (see Figure 11.23):
node dad-jokes.js
Now you can enjoy all the dad jokes you can handle thanks to Copilot! I
hope this example shed light on just how useful Copilot can be in the context
of Neovim/Vim.
For more extensive documentation, visit the DOC file for the Copilot Vim plugin.
https://github.com/github/copilot.vim/blob/release/doc/copilot.txt
180 Part III ■ Practical Applications of GitHub Copilot
Prerequisites
■■ GitHub Copilot license
https://github.com/features/copilot
■■ GitHub CLI
https://cli.github.com
If you want to upgrade your Copilot extension, you can run the upgrade
command:
gh extension upgrade gh-
copilot
NOTE The first time you run the gh copilot suggest function, you may be
asked to allow GitHub to collect usage data to help improve the product. The data col-
lected does not include your queries.
182 Part III ■ Practical Applications of GitHub Copilot
This will provide you with multiple options. You can get generic shell command,
gh command, or Git command assistance (see Figure 11.25).
In this case, you will see how Copilot can help you find how to search for a
file that contains a specific string (see Figure 11.26).
With this result, you can do many actions. You can copy, explain, execute,
revise, rate, or exit from the result.
Figure 11.27 shows the result if you explain the command and then execute it.
In this result, you can see that Copilot provided a great explanation of the
command. Also, when attempting to directly run the command from Copilot’s
CLI, there was an issue because of not having the ghcs alias set up. You will see
how this is configured at the end of this section.
You can also provide the Copilot suggest feature with the command you
want help with from the first step like this:
gh copilot suggest "Task that you want to run"
Figure 11.27: Copilot explains and executes the generic shell command.
This will initiate a similar experience as the suggest feature but is focused
only on providing you with an explanation of the command instead of the ability
to run it directly from the result (see Figure 11.28).
Bash
PowerShell
Zsh
After you have updated your configuration file, close your shell and re-open
it. You will then have access to use the ghcs and ghce aliases.
References
[1] GitHub, “GitHub Copilot for Vim and Neovim” 2024. [Online].
Available: https://github.com/github/copilot.vim
[2] GitHub, “Using GitHub Copilot in the CLI” 2024. [Online]. Available:
https://docs.github.com/en/copilot/github-c opilot-i n-t he-
cli/using-github-copilot-in-the-cli
Conclusion
In review, I hope this chapter has given you insights into just how helpful GitHub
Copilot is in development environments. The team at GitHub is continuing to
innovate, taking Copilot to more places to assist engineers where they work best.
CHAPTER
12
Universal Conversion with
GitHub Copilot
In this chapter, you will discover the compelling use of GitHub Copilot for
universal conversion in software development. Copilot can assist in translating
languages, frameworks, libraries, databases, or CI/CD pipelines.
With Copilot by your side, you are empowered to transition between tech-
nologies with incredible speed. This opportunity to use the technologies that
you require with speed and accuracy is a game-changing capability.
Let’s jump to the examples of how Copilot can supercharge your development
workflow when translation is required.
■■ Translating Natural Language to Programming Languages
■■ Converting JavaScript Components
■■ Simplifying CSS Styles
■■ Migrating Databases
187
188 Part III ■ Practical Applications of GitHub Copilot
If you would like to follow along with this coding example, you can down-
load a copy of the starter ReactButton.js component in the Chapter 12 folder.
https://www.wiley.com/go/programminggithubcopilot
Here you can see that Copilot created an Angular button component that
has the appropriate naming convention of the file noted and file structure that
Chapter 12 ■ Universal Conversion with GitHub Copilot 191
is best practice for Angular and applies indention correctly. Figure 12.4 shows
the resulting Angular button component.
This could be extended to any other component type that you might need
to convert. Also, this concept can apply to any of the popular front-end frame-
works like Vue.js, Svelte, Ember.js, and more.
If you would like to follow along with this coding example, you can download
a copy of the starter css-to-tailwind-starter.html file in the Chapter 12 folder.
https://www.wiley.com/go/programminggithubcopilot
This screen consists of a name, email, password, and Create Profile button.
The form input is in a form tag that is aligned center with a header above it. All
of this is currently done with inline CSS (see Figure 12.6).
Chapter 12 ■ Universal Conversion with GitHub Copilot 193
You can see that there are many lines of styles per HTML tag supporting
this design and layout. With Copilot’s help, you can convert this page to use a
framework like Tailwind CSS to clean up this markup and make the page much
more maintainable.
To do this, open a chat window with the HTML file open. Send a request to
Copilot like the following:
Convert this html page to use Tailwind CSS #file:css-
to-
tailwind.html
This request should result in a fully formed HTML page that utilizes Tailwind
CSS in place of the pure CSS attributes (see Figure 12.7).
After getting this result, copy the contents of the Tailwind CSS version to the
HTML file. You will notice this is a much more consolidated and cleaner file.
You can then open the HTML file in a browser to see the updated look (see
Figure 12.8).
In addition to the source file improvements, you should notice that the style
updates to the input boxes, button, padding, and colors are all subtly improved.
This is because frameworks like Tailwind CSS and others have great defaults
that give you a nice look right out of the box.
Now, you can take this further by exploring what other UI frameworks Copilot
can assist in translating to. In this case, with the HTML file open, send another
194 Part III ■ Practical Applications of GitHub Copilot
Figure 12.7: Copilot response for converting the page to Tailwind CSS
request to Copilot for an HTML page using Bootstrap like the following (see
Figure 12.9):
Convert this html page to use Bootstrap
You can see that due to the visibility of Tailwind CSS lines within the editor,
you do not need to use the #file tag to give the entire context of the file. In
addition, the generated HTML for the Bootstrap framework aligns to the required
structure for the Bootstrap CSS class attributes to function properly.
After you have reviewed the generated HTML, add it to the editor in place
of the previous HTML and open it in a browser to inspect the differences (see
Figure 12.10).
With this design, you still have the same general layout, with the header above
a centered card that has a drop shadow applied. A larger change between the
two frameworks is the lack of a gray background. There are color classes that
should assist this within Bootstrap if you would like to make further modifi-
cations to the file. Lastly, the Create Profile button is spanning the entire width
of the form input area.
196 Part III ■ Practical Applications of GitHub Copilot
Figure 12.10: HTML page with Bootstrap framework powering design and layout
In this section, you will see some of these translations and how you can easily
enhance your nontyped language with Copilot.
JavaScript to Typescript
Let’s look at how Copilot can help convert JavaScript to TypeScript. In this
example, there is a calculateTotal function that has an input of items and
discount properties and should return the calculated total.
function calculateTotal(items, discount) {
let total = 0;
for (let i = 0; i < items.length; i++) {
total += items[i].price;
}
total -
= total * (discount / 100);
return total;
}
There are several potential issues that could arise when not using TypeScript
in this function. First, type safety when using the input parameters items and
discount is not present. So, if a developer accidentally passes a single item into
the method instead of an array, there would be a runtime error. Also, for the
discount parameter, if a developer later passes a non-numeric value, there would
be a runtime error. While these things can be checked with unit tests, adding
another layer of safety on your code can help identify issues quickly and keep
the maintainability of your code higher.
To convert this function to typescript, let’s use inline chat. You can also use
chat within the window, but for this purpose I will be demonstrating an inline
refactor.
Start by selecting the function. After making the selection, activate inline
chat. Send a request to Copilot to convert the file to TypeScript with the fix
command (see Figure 12.11):
/fix convert the file to TypeScript
After making this conversion, you would need to update your project to use
TypeScript. As stated earlier, nontyped languages offer an ease of use because of
their simplicity and an ease of execution. With the addition of types, it is now a
requirement to do a few additional steps to get your code to compile and execute.
For assistance in these remaining steps, you can turn to Copilot. Start a new
window chat and ask Copilot the following:
How can I update my JavaScript project to use TypeScript?
After sending this request, you should get a detailed step-by-step guide to
implementing TypeScript for your project (see Figure 12.12).
198 Part III ■ Practical Applications of GitHub Copilot
Pandas to Polars
An example of when you might need to translate from one library to another
is when you might have some code that does a process for you that needs to be
modernized for performance considerations. In Python, a popular data processing
library called Pandas is heavily used. While this library is great, when you are
working with large data sets, performance issues could become an issue, and you
might need to consider another option. Here you will see how you can leverage
Copilot to convert a Python Pandas data processing application to use Polars.
Polars is a performance-first data processing library that has benchmarking
tests indicating speed improvements of up to 50x in performance; compared
to Pandas, speed tests from the independent TPC-H Benchmark indicate a 30x
performance improvement over Pandas [1].
Starting from a simple data processing application in Python using Pandas,
you will see how quickly Copilot can assist in translating to Polars.
If you would like to follow along with this coding example, you can down-
load a copy of the starter pandas-to-polars.py file in the Chapter 12 folder.
https://www.wiley.com/go/programminggithubcopilot
From this starting point, select the application code and use the chat window
to ask Copilot to convert the application to use Polars (see Figure 12.13).
Here is the request to Copilot:
Convert application to use Polars #editor
From here, you can use the Inject Code At Cursor option from the window
chat result to apply the new code to the editor.
As you will see in this resulting Polars code, there are slight adjustments to
the methods and parameter syntax for interacting with the dataset.
Here is the completed Python application with Polars:
import polars as pl
With this conversion now completed, you can proceed to installing the appro-
priate library as Copilot indicated in the chat response and enjoy the speed
improvements when dealing with your large dataset.
Express.js to Koa.js
Express.js has long been the go-to framework for developing web applications
in Node.js. It is simple, is unopinionated, and has a large community with a rich
ecosystem of middleware. However, as JavaScript and Node.js have evolved,
new frameworks have emerged that take advantage of newer features to offer
a more modern and streamlined development experience.
One such framework is Koa.js. Developed by the same team behind Express,
Koa.js leverages async functions to eliminate callbacks and significantly improve
error handling. Koa is also modular, enabling for a leaner more dynamic offering.
In this section, you will discover how in the process of modernizing your
framework-dependent applications, Copilot can assist in updating your code to
ensure the functionality is preserved while giving you the benefits of modern
advancements made by new frameworks.
If you would like to follow along with this coding example, you can download
a copy of the starter express-to-koa.js file in the Chapter 12 folder.
https://www.wiley.com/go/programminggithubcopilot
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
202 Part III ■ Practical Applications of GitHub Copilot
Using Copilot Chat, let’s see how you can translate this application to Koa.js.
Start by opening a window chat and request Copilot to convert the application
to use Koa.js (see Figure 12.14).
Here is the request to Copilot:
Convert application to use Koa.js #editor
From here, you can take this application code using Koa.js and apply it to
your editor. There are several differences here from the use of a Koa router
library to async functions. With Copilot, you can remove the burden of making
each individual edit to your application code when migrating frameworks as
you have seen here.
Here is the completed Node.js application using Koa.js:
const Koa = require('koa');
const Router = require('@koa/router');
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
Objective-C to Swift
For years, the preferred language to create macOS and iOS applications was
Objective-C. While this language allowed for a great ecosystem of applica-
tions to be developed and tooling to be created, modernization efforts for
the Apple ecosystem resulted in the creation of the Swift programming lan-
guage. As a result, the developer community began to have more and more
reasons to migrate to Swift because of its continued feature enhancements
and first-class support.
Let’s look at an example of an Objective-C class that Copilot can assist in
translating to Swift.
If you would like to follow along with this coding example, you can down-
load a copy of the starter Person.m file in the Chapter 12 folder.
https://www.wiley.com/go/programminggithubcopilot
204 Part III ■ Practical Applications of GitHub Copilot
-(instancetype)initWithFirstName:(NSString *)firstName
lastName:(NSString *)lastName;
- (void)printFullName;
@end
@implementation Person
-(instancetype)initWithFirstName:(NSString *)firstName
lastName:(NSString *)lastName {
self = [super init];
if (self) {
_firstName = firstName;
_lastName = lastName;
}
return self;
}
-(void)printFullName {
NSLog(@"%@ %@", self.firstName, self.lastName);
}
@end
In this example, you will see how Copilot can translate code using inline
comments to drive code completion for the translation task. This may not be
the ideal method for translating a class file, but I wanted to showcase another
option if you are in an IDE without chat support but would still like to trans-
late a class file.
In an editor window, add the following two blank lines after the Objective-C
Person object and input a comment like the following:
// Convert the above code to Swift
After inputting that comment, you can proceed to the next line; in my case
Copilot suggests a name for the Person.swift file we want to create. After add-
ing a new line after that, you should get an import for the Foundation library.
Add that line, and add two more blank lines after the import. This should
trigger Copilot to suggest a completion for the Person class (see Figure 12.15).
Chapter 12 ■ Universal Conversion with GitHub Copilot 205
Migrating Databases
Migrating databases can be a huge effort. Although there are great tools to assist
in large portions of migrations, there are still some manual tasks that Copilot
can assist with. Whether you are moving from MySQL, PostgreSQL, SQL Server,
or Oracle Database, you can lean on your pair-programming assistant GitHub
Copilot to help you along the way.
In this section, you will learn how Copilot can assist with general database
conversion tasks.
https://www.wiley.com/go/programminggithubcopilot
EXEC GetFullName 1;
Using Copilot Chat, you can make quick work of a small, targeted conversion.
With the SQL Server database file open, request that Copilot convert to PostgreSQL.
Convert from SQL Server to PostgreSQL
After sending this request to Copilot, you should get a resulting PostgreSQL
file that you can use as a baseline to your migration efforts (see Figure 12.16).
As mentioned, there are great tools that can support large migration efforts,
but sometimes the ease of use with Copilot for targeted migrations can be a
much better option. Also, a tool like pgloader does not migrate SQL Server
stored procedures to PostgreSQL functions. This is a great area to get Copilot
to assist and quickly migrate those files to your new database.
When transitioning to a new CI/CD platform, the files that define CI/CD
pipelines are invaluable assets. These files, typically scripted in YAML or JSON,
contain detailed descriptions of the build, test, and deployment processes that
software goes through from development to production. Utilizing these files
effectively can facilitate a smoother transition to a new platform, and tools like
GitHub Copilot can significantly enhance this process by assisting in translating
and adapting these infrastructure files to your target CI/CD platform.
In this example, Copilot will be used to translate the .yaml file for an Azure
DevOps pipeline to GitHub Actions. The example will showcase a Copilot Chat
conversation that references an Azure DevOps pipeline file for context.
If you would like to follow along with this coding example, you can down-
load a copy of the starter ado.yaml file in the Chapter 12 folder.
https://www.wiley.com/go/programminggithubcopilot
Here is the chat request to Copilot to convert an Azure DevOps pipeline file
to GitHub Actions:
Convert this Azure DevOps pipeline file to GitHub Actions:
trigger:
- master
208 Part III ■ Practical Applications of GitHub Copilot
pool:
vmImage: 'windows-
latest'
variables:
solution: '**/*.sln'
buildPlatform: 'Any CPU'
buildConfiguration: 'Release'
steps:
-task: NuGetToolInstaller@1
-task: NuGetCommand@2
inputs:
restoreSolution: '$(solution)'
-task: VSBuild@1
inputs:
solution: '$(solution)'
msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package
/p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true
/p:DesktopBuildPackageLocation="$(build.artifactStagingDirectory)\
WebApp.zip"
/p:DeployIisAppPath="Default Web Site"'
platform: '$(buildPlatform)'
configuration: '$(buildConfiguration)'
-task: VSTest@2
inputs:
platform: '$(buildPlatform)'
configuration: '$(buildConfiguration)'
-task: PublishBuildArtifacts@1
-task: AzureRmWebAppDeployment@4
inputs:
ConnectionType: 'AzureRM'
azureSubscription: 'Your Azure Subscription'
appType: 'webApp'
WebAppName: 'Your Web App Name'
packageForLinux: '$(build.artifactStagingDirectory)/**/*.zip'
After sending this request to Copilot, you should get a result that details the
resulting GitHub Actions workflow file and indicates any manual updates that
might be needed due to different build dependencies (see Figure 12.17).
As you can see from this example, both platforms allow .yaml file formats,
but the structure and keywords are different. Azure DevOps Pipelines use
a more linear structure, while GitHub Actions use a more nested structure.
GitHub Actions also make extensive use of “actions,” which are reusable
pieces of code.
Chapter 12 ■ Universal Conversion with GitHub Copilot 209
Figure 12.17: Copilot response for Azure DevOps pipeline file to GitHub Actions
more rows to fetch, displaying the ID, name, and balance for each row. When
it’s done, it closes the cursor and disconnects from the database.
If you would like to follow along with this coding example, you can download
a copy of the starter CustomerBalanceDisplay.cob file in the Chapter 12 folder.
https://www.wiley.com/go/programminggithubcopilot
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-ID PIC 9(5).
01 WS-NAME PIC X(20).
01 WS-BALANCE PIC 9(5)V99.
01 WS-EOF PIC X VALUE 'N'.
PROCEDURE DIVISION.
Begin.
EXEC SQL
CONNECT TO DB2
END-
EXEC.
EXEC SQL
DECLARE C1 CURSOR FOR
SELECT ID, NAME, BALANCE
FROM CUSTOMERS
END-
EXEC.
EXEC SQL
OPEN C1
END-
EXEC.
EXEC SQL
CLOSE C1
Chapter 12 ■ Universal Conversion with GitHub Copilot 211
END-
EXEC.
EXEC SQL
DISCONNECT DB2
END-
EXEC.
STOP RUN.
Let’s see how Copilot can convert this legacy program to a C# equivalent.
Start by opening VS Code with the CustomerBalanceDisplay.cob file opened.
After having that file open, start a new chat with Copilot and send a request
like the following:
Convert this COBAL program to C#. #file:CustomerBalanceDisplay.cob
After sending this request, you should get a result from Copilot that matches
something like the following program file:
using System;
using System.Data;
using IBM.Data.DB2;
namespace DB2Example
{
class Program
{
static void Main(string[] args)
{
string connectionString = "your_connection_string_here"; //
replace with your DB2 connection string
}
}
connection.Close();
}
}
}
}
In this program, you can see that Copilot did a great job preserving the func-
tionality of the legacy COBAL application while modernizing the codebase to
C#. Because no additional instructions were given, Copilot determined we most
likely wanted to preserve the DB2 database connection. In some cases, you might
want to migrate to a new database technology as well. In this next example,
you will see how Copilot can also implement a new database technology and
migrate the code functionality all at the same time.
Start this by sending a new request to Copilot like the following:
Convert this COBAL program to C#. Use SQL Server and Entity Framework.
#file:CustomerBalanceDisplay.cob
With this request, you are specifying the original request to convert the program
to C#. In addition, you can layer on additional instructions to use SQL Server and
the Entity Framework. It is important not to try to get Copilot to do conflicting
tasks or overload your requests. In this example, it works out well to convert the
database connection code and program code simultaneously. Using this request,
you should get a result that describes the Entity Framework class and context
files and an updated CustomerBalanceDisplay program file (see Figure 12.18).
In addition to the instructions and Entity Framework class files, Copilot should
respond with the updated program class, resulting in something like this:
public class Program
{
public static void Main(string[] args)
{
using (var context = new CustomerContext())
{
var customers = context.Customers.ToList();
Figure 12.18: Copilot response for converting COBAL program and DB2 to SQL Server
With the help of Copilot, this program becomes more maintainable and easier
to read. Using the Entity Framework has reduced the program code significantly.
Using this framework also gives type safety when working with database objects
enhancing the stability of the program.
Conclusion
In this chapter, you explored the transformative capabilities of Copilot in facil-
itating seamless transitions across a multitude of technical landscapes. When
converting languages, frameworks, libraries, databases, or CI/CD pipelines,
Copilot not only accelerates the adoption of new technologies but also enhances
the development workflow with unparalleled speed and accuracy. Through
various examples, you saw how Copilot can be leveraged to do the following:
■■ Translate natural languages into programming languages, simplifying
the bridge between concept and implementation.
■■ Convert JavaScript components, making the shift between different
JavaScript frameworks less daunting.
214 Part III ■ Practical Applications of GitHub Copilot
Reference
IV
Key Insights and Advanced Use
Cases for GitHub Copilot
In This Part
Chapter 13: Considering Responsible AI with GitHub Copilot
Chapter 14: Augmenting the Software Development Lifecycle with GitHub
Copilot
Chapter 15: Exploring Copilot Business and Enterprise
CHAPTER
13
Considering Responsible AI with
GitHub Copilot
In this chapter, you will learn about responsible AI, what AI regulations are
being established by governments, how GitHub Copilot implements respon-
sible AI principles, and what you should consider when adopting AI-powered
tools like GitHub Copilot.
■■ Introducing Responsible AI
■■ Examining How GitHub Copilot Implements Responsible AI
■■ Programming with AI Responsibly
Introducing Responsible AI
Responsible artificial intelligence (responsible AI) refers to the practice of cre-
ating, evaluating, and implementing AI technologies in a manner that is safe,
reliable, and aligned with ethical principles.
In recent years, a plethora of AI tools have emerged. With this surge in
AI-powered tools and mass adoption of AI tooling at a global scale, responsible
AI has never been more important.
The concept of AI has been around since the 1950s, but only recently has the
convergence of hardware, software, and data combined to produce the rapid
advancements seen today with tools like GitHub Copilot. This convergence of
217
218 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
Responsible AI Regulation
The European Union AI Act is setting the stage globally for the adoption of
responsible AI practices [1]. Once in force, the act will impact companies building,
selling, and marketing AI in the EU. Due to the Brussels effect, a term that is used
to describe an incentive for companies to adhere to regulatory standards in a
particular market, I predict that other countries will essentially copy and paste
the act for their own use. The act focuses on establishing an AI risk threat level
that declares banned applications and sets requirements for high-risk systems,
as well as establishing transparency requirements and implementing measures
to support innovation while protecting citizens of the EU. Fines for violations
of the EU AI Act can be as high as 7% of a company’s global revenue, making
this not only the first but the most serious regulation on AI.
In the United States, the White House has established a blueprint for an
AI Bill of Rights, a nonbinding set of responsible AI considerations meant to
generate conversation around establishing protections for U.S. citizens and
residents in the same way the Constitutional Bill of Rights establishes protec-
tions [2]. President Biden also signed an AI Executive Order, which establishes
requirements for the safe implementation and monitoring of AI systems in the
U.S. federal government. This Executive Order was the first government-wide
establishment of responsible AI requirements by a major global power.
Together, these major pieces of regulation, while incomplete and noncompre-
hensive, highlight that global leaders are seeing the importance of clear guidance
and regulations that ensure their citizens are protected and benefit positively
from the advancements in AI.
The GitHub Copilot Trust Center is a great resource that provides videos,
FAQs, and resources specific to GitHub Copilot, which can help you under-
stand some important information that individuals and organizations should
consider when adopting GitHub Copilot into their development workflow [4].
In this section, you will learn how GitHub’s dedication to responsible AI shows
up across the six Microsoft responsible AI principles. The following examples do
not represent an exhaustive list of GitHub’s implementations of responsible AI
considerations into the product but provide insight into some of the intentional
responsible AI decisions made in the development of the product.
Fairness
The idea behind the fairness principle is that “AI systems should treat all people
fairly” [6]. One example of fairness considered by the GitHub Copilot team
is ensuring that the tool operates in languages other than English. In devel-
oping the tool, the GitHub team ensured that natural language support was
established for a large set of languages. The default language can be adjusted
in the extension settings for Copilot (see Figure 13.1).
In Figure 13.2, you can see how, when setting a default response language
for Copilot, you will receive responses specific to the locale.
red teaming to ensure Copilot can respond safely when provided with malicious
requests.
In addition to red teaming, GitHub has an extensive bug bounty program
that allows for talented security researchers to submit bugs they find within
the GitHub services [5].
An example of this built-in protection is when a user might request detailed
information on how to perform a cross-site scripting attack. Copilot will resist
providing information on this topic (see Figure 13.3).
Data Protection
GitHub Copilot is compliant with the General Data Protection Regulation
(GDPR). GDPR is Europe’s data privacy and security law. This regulation works
222 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
to protect consumer data and enforce fines on companies that do not have their
data privacy and security standards in place.
For business and enterprise users, data used for GitHub Copilot code sug-
gestions and chat responses are not stored in persisted storage. Instead, this
data is kept in memory only for the duration of the API request. Once that is
completed, the request data is cleared. Also, to further ensure your session data
is protected, GitHub does not log user request data.
For individual plan users, prompts and suggestions are retained by default
unless you disable code snippet collection in your settings.
Inclusiveness
The principle of inclusiveness establishes the idea that “AI systems should
empower everyone and engage people” [6]. One way that GitHub fosters inclu-
siveness is by providing several options to obtain a license to GitHub Copilot,
which works to make the product available for everyone. For students and
maintainers of popular open-source projects, Copilot can be completely free. For
individuals, the current price is $10 per month or $100 per year. And there are
also multiple options for organizations to purchase the plan that fits their needs.
Another example of inclusiveness is that GitHub Copilot does not operate on
its own in the background while the programmer works. The tool was never
intended to replace programmers or make them obsolete. It partners with the
programmer, which keeps them included in the work being done. This is great
for the labor market, but it also lends to the principle of accountability, which
I’ll dive into in a moment.
Transparency
The idea of the principle of transparency is that “AI systems should be under-
standable.” To illustrate this principle, you can ask GitHub Copilot Chat to
explain the code that it has written for you (see Figure 13.5). This is an example
of transparency in that it allows the user to understand what’s being offered in
terms of a code suggestion.
Another way you can see this principle show up in practice is in the docu-
mentation and explanation of how the product works. GitHub did not create
GitHub Copilot to operate in a black box. It was created in a way that lends to
transparency and allows users to understand how the product is working, how
it is trained, the data it leverages, and the code it produces.
Accountability
The accountability principle posits that “People should be accountable for AI
systems.” While every principle is important, this is perhaps the most critical.
Because of the pace of AI development and the very real impact AI can have—
positively and negatively—on human lives, it could be easy to get into a loop
of blaming AI for being unsafe, providing unfair responses, or sharing biased
views and perspectives.
224 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
In addition to checking for accuracy, inspecting the generated code for secu-
rity vulnerabilities is always encouraged. Copilot, like any other programmer,
can make mistakes, and you should do your best to validate generated code
for security compliance.
Another example of accountability with GitHub Copilot is the Copilot Copy-
right Commitment from Microsoft. With this commitment, Microsoft has pledged
support for business and enterprise Copilot customers [7]. The GitHub Copilot
product-specific terms in the “Defense of Third Party Claims” section details
the protections offered under this agreement [8].
Further Research
For full details on these responsible AI principles, please visit the Microsoft
Responsible AI website.
https://www.microsoft.com/ai/responsible-ai
For more details on how GitHub Copilot works and information about respon-
sible AI related to the product, visit the GitHub Copilot Trust Center.
https://resources.github.com/copilot-trust-center
226 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
Conclusion
This chapter provided a high-level exploration of responsible AI, detailing the
regulations set forth by governments, the application of responsible AI princi-
ples in GitHub Copilot, and considerations for adopting AI-powered tools like
GitHub Copilot. You should now have a good starting point to understand and
engage with AI technologies ethically and effectively.
Chapter 13 ■ Considering Responsible AI with GitHub Copilot 227
References
14
Augmenting the Software
Development Life Cycle with
GitHub Copilot
In this chapter, we will explore the details of the software development life
cycle (SDLC) and how GitHub Copilot can help you each step of the way.
We will assess the current adoption statistics of AI tooling in the SDLC and
future predictions. Additionally, we will define the levels of AI integration in the
SDLC. Finally, this chapter will address potential concerns with ever-increasing
AI adoption in software development workflows and what impacts adoption
might have on job stability and work dynamics.
■■ Introducing the SDLC
■■ Assessing the Adoption of AI in the SDLC
■■ Detailing Levels of AI Integration in the SDLC
229
230 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
tenance
Main 6
Re
5 q
uir
em
nt
ent
yme
s
Deplo
Software 1
Development
4 Life Cycle
ig n
D es
Te
s
ti n
2
g
3 C o din g
The primary goal of the SDLC is to facilitate the creation of successful soft-
ware releases. Recognizing the complexities of software development, teams
use the SDLC’s structured methodology to build, test, and deliver software that
is ready for production, ensuring the final product is robust and reliable. Let’s
detail the activities of each of these phases and how GitHub Copilot can assist
in each step of the SDLC.
Requirements
In the Requirements phase, the primary activities involve gathering and defining
requirements, documenting specifications, and prioritizing features. GitHub
Copilot can significantly enhance this stage by suggesting documentation tem-
plates, assisting in expanding initial requirement needs into features, brain-
storming requirements details, and even writing requirement specifications
based on your guidance.
Design
During the Design phase, activities such as creating architectural diagrams,
designing user interfaces, and planning system interactions are crucial. GitHub
Copilot assists here by generating boilerplate code for design patterns, offering
coding alternatives, and suggesting improvements or best practices based on
current design trends.
Chapter 14 ■ Augmenting the Software Development Life Cycle 231
Coding
The Coding phase is where GitHub Copilot truly excels, helping you write
code, review code, and integrate modules. It provides real-time code sugges-
tions, completes lines or blocks of code, and helps you write more efficient,
error-free code quickly.
Testing
In the Testing phase, writing test cases, conducting various types of tests, including
unit, integration, and system tests, debugging, and validating are key activities.
GitHub Copilot aids by suggesting and generating test cases, helping identify
potential edge cases, and providing code for automated testing frameworks to
enhance the robustness and coverage of tests.
Deployment
The Deployment phase involves configuring servers, deploying code to produc-
tion, and monitoring the deployment process. GitHub Copilot offers guidance
on deployment scripts, suggests best practices for CI/CD pipelines, and helps
troubleshoot deployment issues by providing relevant code snippets and
configurations.
Maintenance
During the Maintenance phase, activities such as bug fixing, upgrading systems,
and optimizing performance are prevalent. GitHub Copilot helps by quickly
identifying bugs with suggested potential fixes, offering performance optimiza-
tion techniques, and assisting in updating documentation or comments within
the code to maintain its relevance and readability over time.
Early Majority
Late Majority
Early Adopters
Innovators Laggards
Level 5
Optimizing
Level 4
Quantitatively Managed
Level 3
Defined
Level 2
Managed
Level 1
Initial
Level 0
Nonexistent
Level 0: Nonexistent
At level 0, AI integration in the SDLC is virtually absent. This stage is character-
ized by a complete lack of AI tools and processes within the development frame-
work. Organizations at this level rely solely on traditional software development
practices, without the augmentation of AI capabilities.
At this level, there is high potential for misuse of AI tools by engineering teams
due to lack of clarity from the organization on proper use and best practices.
This lack of clarity and misuse can lead to organizational risk.
As discussed in the previous section, developers surveyed directly are adopt-
ing AI tooling at a high rate while organizations are not yet identifying their
adoption rates at as high a rate [2, 3]. This indicates that there is most likely a
large number of organizations with no guidance on AI integration in the SDLC
while their engineering teams are seeking out AI tooling on their own.
234 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
Capabilities Demonstrated
These are the capabilities:
Traditional Development Approaches Development processes are manual
and follow conventional methodologies without the support of AI-driven
insights, automation, or efficiency enhancements.
Limited Awareness or Understanding There may be little to no organiza-
tional awareness of the potential benefits that AI integration could bring
to the software development process. This lack of understanding extends
to both the managerial level and the development team.
Reactive Problem-Solving Without AI tools, problem-solving approaches are
reactive rather than proactive. Issues are addressed as they arise, without
the predictive capabilities or data-driven insights that AI could provide.
No AI-Driven Optimization Processes such as coding, testing, and deploy-
ment lack optimization that could be achieved through AI techniques such
as machine learning models, natural language processing, and automated
testing frameworks.
Level 1: Initial
At level 1, organizations begin their journey toward AI integration within the
SDLC by exploring and tentatively adopting AI tools and methodologies. This
level is characterized by initial efforts to understand and implement AI capa-
bilities in a limited, experimental fashion, often focused on specific projects or
parts of the SDLC.
Capabilities Demonstrated
These are the capabilities:
Basic AI Tool Experimentation Teams start to experiment with basic AI tools,
such as code completers, simple bug detection algorithms, or automated
code reviewers, to gain familiarity with AI’s potential applications in
software development.
Initial Data Analysis Efforts There’s an emerging effort to use AI for ana-
lyzing development data, such as code repositories or bug reports, to
extract insights that could inform development decisions, albeit in a rudi-
mentary form.
Ad Hoc AI Integration in Projects AI integration is sporadic and project-
specific, lacking a cohesive strategy across the organization. Projects selected
for AI integration serve as pilots to understand the benefits and challenges
of using AI in development.
Chapter 14 ■ Augmenting the Software Development Life Cycle 235
Level 2: Managed
At level 2, organizations have moved beyond the initial exploration of AI in
the SDLC to a phase of managed integration, where AI tools and practices are
implemented with specific management oversight and integration into selected
development processes. This level is marked by a deliberate approach to AI
adoption, driven by targeted objectives and monitored through structured
management practices.
Capabilities Demonstrated
These are the capabilities:
Targeted AI Implementation AI technologies are selected and deployed
based on their ability to meet specific development goals or solve identi-
fied challenges, such as improving code quality, enhancing efficiency, or
automating repetitive tasks.
Process-Specific AI Integration AI tools are integrated into stages of the
SDLC where they can provide the most significant benefits, with efforts
managed and monitored to ensure alignment with development objectives.
Management of AI Tools and Processes The use of AI in software
development is actively managed, with clear roles and responsibilities
defined for overseeing AI integration, ensuring that AI tools are used
effectively and in accordance with organizational policies.
Performance Measurement The impact of AI integration on development
processes are systematically measured against predefined metrics, allow-
ing for the evaluation of AI’s contribution to development goals and the
identification of areas for improvement.
Level 3: Defined
At level 3, organizations achieve a phase of defined integration in the adoption
of AI within the SDLC. This level signifies a mature approach where AI tools
and methodologies are not just managed but are fully integrated into standard-
ized processes across the organization. AI practices are documented, and their
integration is characterized by consistency, repeatability, and alignment with
the organization’s strategic goals.
236 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
Capabilities Demonstrated
These are the capabilities:
Standardized AI Processes The organization has developed and implemented
standardized processes for integrating AI tools across various stages of
the SDLC. These processes are documented and shared across teams,
ensuring consistency in how AI is leveraged for software development.
Organization-wide AI Integration AI integration extends beyond specific
projects or teams and is now a standard part of the development process
across the organization. This widespread adoption ensures that all projects
benefit from AI’s efficiency and innovation potential.
Comprehensive AI Strategy There exists a comprehensive strategy for AI
adoption that aligns with the organization’s overall business and tech-
nology objectives. This strategy guides the selection, implementation, and
management of AI tools and processes.
Advanced AI Use Cases The organization is implementing advanced AI
use cases, such as deep learning for complex problem-solving, AI-driven
user experience personalization, and predictive analytics for strategic
planning and decision-making.
Capabilities Demonstrated
These are the capabilities:
Advanced Metrics and KPIs The organization implements a comprehen-
sive set of metrics and key performance indicators (KPIs) to measure the
effectiveness, efficiency, and impact of AI tools and methodologies on the
software development process.
Data-Driven Process Improvement AI integration processes are subject
to continuous analysis and improvement based on quantitative data.
This approach allows for the fine-tuning of AI strategies to maximize
development outcomes and organizational objectives.
Chapter 14 ■ Augmenting the Software Development Life Cycle 237
Level 5: Optimizing
At level 5, organizations have achieved the pinnacle of AI integration within
the SDLC, where AI-driven processes are not only quantitatively managed but
are also continuously optimized for peak performance and innovation. This
stage is characterized by the organization’s proactive and strategic use of AI to
drive ongoing improvements and achieve competitive advantages in software
development and product innovation.
Capabilities Demonstrated
These are the capabilities:
Continuous Process Optimization AI integration processes are continu-
ously analyzed and refined, with adjustments made in real-time based on
performance data, emerging trends, and strategic objectives. This includes
optimizing AI tools and methodologies to enhance efficiency, quality, and
speed across the SDLC.
Innovative AI Application The organization leverages cutting-edge AI
technologies and explores innovative applications of AI in software
development, such as advanced machine learning models for predictive
development analytics, AI-driven user experience design, and intelligent
automation of complex development tasks.
Strategic AI Evolution AI strategies and initiatives are dynamically evolved
to align with changing business goals, technology advancements, and
market demands. The organization remains agile, adapting its AI capa-
bilities to support strategic pivots or capitalize on new opportunities.
Enterprise-wide AI Culture A culture of innovation and continuous improve-
ment pervades the organization, with AI and data-driven decision-making
at the core of not just software development but all business practices.
Employees across the organization are engaged in leveraging AI for opti-
mization and innovation.
238 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
Summary
This section described the various levels of AI integration within the SDLC,
modeled after CMMI. It outlines a progression from level 0 to 5.
This structured approach of evaluation should help you and your organization
assess your current AI maturity level and strategize advancements to enhance
development effectiveness and competitive positioning.
receive personalized meal suggestions, all aimed at reducing waste and sup-
porting a healthier lifestyle.
The development team faces the challenge of seamlessly integrating various
technologies into FreshFridge, ensuring user-friendliness while incorporating
complex AI functionalities. They decide to utilize GitHub Copilot throughout
their Scrum process, enhancing efficiency and powering greater creativity from
requirements research to release management.
Requirements Gathering
The product owner, Sofia, uses GitHub Copilot to efficiently draft detailed
functional requirements and user stories for the FreshFridge’s inventory tracking,
recipe suggestion, and grocery replenishment features, ensuring a comprehen-
sive approach to sustainable living.
In this instance, you will see Copilot used within the VS Code IDE. With
GitHub Copilot Enterprise, the product owner could use GitHub Copilot Chat
within GitHub.com.
Starting with the first requirement that the team has outlined, Sofia opens VS
Code and starts a window chat with Copilot. Here she can request that Copilot
give a list of potential user stories supporting the inventory tracking require-
ment (see Figure 14.4).
Figure 14.4: Copilot responding with user story titles for a feature
240 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
These stories give a great starting point to the Scrum team to be able to iterate
quickly on the baseline requirements for the inventory tracking feature.
Let’s see how GitHub Copilot can create acceptance criteria for the generated
user stories (see Figure 14.5).
Figure 14.5: Copilot responding with user story acceptance criteria in gherkin format
From here, Sofia can upload these stories and acceptance criteria to the product
backlog for her team to review in their product backlog refinement meeting. Or,
if there are changes that she would like to make, she can simply ask Copilot to
make the adjustment to the acceptance criteria, allowing her and her team to
rapidly iterate on the details of the user story.
As you can see from the request made in the example, the prompt simply
indicated “ac” instead of fully spelling out “acceptance criteria.” Because Copilot
is trained on such a large dataset, it can predict the intent of the prompt and
still produce a response that meets our needs.
242 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
The acceptance criteria with the scenarios are a great start for the team. Dur-
ing the PBR meeting, the team discusses the story and scenarios to determine
if they need to add any detail or change. One important element they need to
understand is the AI vision system they will use to complete this work. Know-
ing this will help them size the work item with accuracy.
Let’s examine how Tom, the technical lead, uses Copilot to investigate a vision
system that could be used. First, he can ask a question with the story open in
his VS Code editor for context (see Figure 14.6).
Here’s the request to Copilot:
Are there any AI vision system libraries that should be considered to
accomplish this story?
In the result options, OpenCV stands out as a good option for the team to
try. They determine that they feel confident in their ability to complete the user
story based on their research.
Chapter 14 ■ Augmenting the Software Development Life Cycle 243
This is just one example of ideation and a question that you can leverage
with Copilot. There are endless options to leverage Copilot in the context of
user story discovery and ideation.
With this new information, Tom can make an edit to the scenario by lever-
aging the Copilot inline chat (see Figure 14.7).
Here’s the request to Copilot:
Update this scenario to indicate the use of the OpenCV library.
As you can see, Copilot is highly capable of editing documentation using the
same refactoring techniques used in other sections.
With this tight feedback loop from the discovery to editing of the story, the
FreshFridge team can move faster than ever have before with better knowledge
and more accurate edits to their requirements.
Figure 14.7: Copilot inline chat assisting in edits to a user story scenario
Figure 14.8: Copilot inline chat assisting in tasking of work for a user story
Chapter 14 ■ Augmenting the Software Development Life Cycle 245
The results from Copilot are great. They provide a very logical starting point,
which the team can build from. See the complete list generated by Copilot here:
■■ Research and understand the OpenCV library and its capabilities in image
recognition.
■■ Collect a diverse dataset of food items for training the AI model.
■■ Preprocess the dataset for the AI model (this may include resizing images,
normalization, etc.).
■■ Develop the AI model using a suitable machine learning or deep learning
framework.
■■ Train the AI model with the preprocessed dataset.
as expected.
■■ Refine and retrain the model as necessary based on test results.
ing standards.
■■ Conduct a final review of the user story to ensure all requirements are met.
Now, Alexi can continue to install the required library. With this completed,
they can continue to the next task for this sprint item:
Develop a function/method that uses the trained AI model and OpenCV to identify
and categorize new food items.
246 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
Figure 14.9: Copilot inline chat assisting in installing and importing a library
At this point, Alexi can use a variety of Copilot features to complete the work.
A top-level comment, window chat, or inline chat would work great here. Let’s
see how the team can use inline chat to create a great starting point for a function
that matches the requirements from the task selected (see Figure 14.10).
Here’s the request to Copilot:
Develop a function/method that uses the trained AI model and OpenCV to
identify and categorize new food items.
As you can see from this example, the team generated an identify_food
function from the task text. This completion was assisted by the file, file type,
import statement, and request text.
From here, the developer can continue to interact with Copilot to implement
the missing imports and methods that will finalize the implementation.
Figure 14.10: Copilot inline chat assisting in completing a function for using a trained AI model
for item identification and categorization
Using the Copilot inline chat, the developer can select the code within the
image_processing.py class. After selecting the code and activating inline chat,
they can send the /tests command to create a test file and baseline test asserts
(see Figure 14.11).
Here is the complete test file created by Copilot:
import unittest
from image_processing import identify_food
class TestImageProcessing(unittest.TestCase):
def test_identify_food(self):
# Test case 1: Image with a single food item
image_path = 'path_to_image_with_single_food_item.jpg'
expected_categories = ['apple']
self.assertEqual(identify_food(image_path), expected_categories)
if __name__ == '__main__':
unittest.main()
As you can see, this test is a great example of the power and speed that you
have at your fingertips with GitHub Copilot. From here, the development team
can iterate on the design of the underlying code until it has successfully passed
the unit tests.
Figure 14.11: Copilot inline chat assisting in the creation of unit tests
Chapter 14 ■ Augmenting the Software Development Life Cycle 249
Figure 14.12: Copilot Chat response for integration pipeline workflow file
on:
push:
branches: [ dev ]
pull_request:
branches: [ dev ]
jobs:
build:
runs-
on: ubuntu-
latest
steps:
-uses: actions/checkout@v2
with:
python-
version: '3.11'
As you can see, Copilot’s chat response gives a step-by-step instruction set
with a complete workflow file to kick-start the integration of the new feature
work from the team. Also, Copilot uses the Python version from the request in
the generated result.
These examples showcase how GitHub Copilot can be utilized at every
phase of the SDLC. This was just a glimpse at the numerous ways a development
team can leverage Copilot while working on sprints.
Conclusion
In this chapter, you learned about the SDLC and how AI can be integrated into
a Scrum team’s workflow. Copilot can be helpful in every phase of the SDLC.
We explored the current adoption statistics and future predictions detailing
what today’s development landscape looks like and where we are headed. These
statistics and predictions emphasize the upward trajectory of GitHub Copilot
in the software industry.
Additionally, you learned about the levels of AI integration in the SDLC. From
level 0 to level 5, you should be empowered to address where you are in your
organization’s adoption of AI in the SDLC and be able to navigate a way forward.
Finally, this chapter addressed potential concerns with ever-increasing AI
adoption in software development workflows and the impact that might have
on job stability and work dynamics.
References
[3] GitHub, 2023. “Survey reveals AI’s impact on the developer experi-
ence,” h ttps://github.blog/2023-06-13-survey-reveals-ais-impact-
on-the-developer-experience
[4] ISACA, 2024. “What is CMMI?,” https://cmmiinstitute.com/
cmmi/intro
[5] GitHub, 2024. “GitHub Copilot Trust Center,” https://resources
.github.com/copilot-trust-center
CHAPTER
15
Exploring Copilot Business
and Enterprise
This chapter will cover the features within Copilot Business and Copilot
Enterprise. Building on the robust offerings of the Copilot experience, Copilot
Business enables organizations to leverage Copilot while giving leaders the
control they need and ensuring the security of their intellectual property.
In addition to the controls and security that Copilot Business offers, you
will learn the advanced capabilities of Copilot Enterprise. These robust fea-
tures enable your entire organization to get more done. You will learn about
chat within GitHub.com, indexing repositories, knowledge bases, pull request
features, and more.
■■ Introducing Copilot Business and Enterprise
■■ Chatting with Copilot in GitHub.com
■■ Indexing Code Repositories to Improve Copilot’s Understanding
■■ Looking Ahead
253
254 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
With GitHub Copilot in the CLI, you can interact with Copilot in a whole
new way. Assisting with command suggestions and explanations, the ability
to gain insights and get executable results from Copilot is a powerful addition
to the already highly effective set of tooling in the IDE.
In the “Managing GitHub Copilot” section, you will learn the details for how
you can do content exclusion, manage access to Copilot, update and refine pol-
icies for allowed use, and review audit logs [1].
For a full list of features and extended documentation for Copilot Business,
please head to the GitHub Copilot Business feature set documentation page.
https://docs.github.com/enterprise-cloud@latest/copilot/
copilot-business/github-copilot-business-feature-set
All the remaining features discussed in this chapter will be exclusive to Copilot
Enterprise, except for the GitHub Copilot management features.
Throughout the remainder of this chapter, you will see examples of all these
features in action.
Here you will see an introduction from Copilot with a search field for repos-
itories, a list of your most recently accessed repositories, and an option to start
a general-purpose chat.
Chapter 15 ■ Exploring Copilot Business and Enterprise 259
Let’s see how we can chat with Copilot about a specific repository. In the
search input field for the repositories, search for “codeql.” You should see a list
of options to choose from (see Figure 15.5).
Here you can see Copilot has utilized the repository index to find the
CONTRIBUTING.md file and embed that result within the reply. There are several
great links that point you in the right direction to being a pull request.
Additionally, Figure 15.6 showcases the immersive chat view. This view is
accessible from the ellipse menu at the top right of the chat window. You can see
that this changes the URL to github.com/copilot and adds the unique identifier
for the conversation to the route. This enables you to pin a conversation or the
immersive view to your bookmarks if you want to have a quick entry point to
Copilot in GitHub.com.
After opening this new conversation, you should be presented with a welcome
statement from Copilot reminding you to review the output carefully before
use; it’s always good to take note of. Copilot can and will make mistakes due to
the nature of the technology. It is up to you to ensure the quality of the output
and help guide Copilot to give quality responses.
In addition to the notification at the top, you should see conversation sug-
gestions at the bottom of the screen. These are useful to help you explore the
robust abilities of Copilot. From backend infrastructure as code to front-end
frameworks, Copilot can assist you to research, refine, and implement bespoke
solutions for your needs (see Figure 15.7).
While you will have different suggested conversation prompts each time, in this
case, I will choose the conversation prompt for a walk-through on Vue.js essentials.
Unlike the previous chat example with a repository referenced, this response
is generated from the large language model of GitHub Copilot without the
embedded resources of a GitHub repository file (see Figure 15.8).
Copilot has provided a great response with details on a default Vue.js app
instance, what critical information you need about directives, general com-
ponent structure, Vue router, Vuex library, Vue CLI, single-file components,
262 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
and reactivity. This robust information about Vue.js provides a great starting
point to be productive with Vue.js.
You can also ask repository-specific questions that could provide you with
more targeted results. This will be covered in the “Indexing Code Repositories
to Improve Copilot’s Understanding” section. There you will find how you can
ask Copilot to assist in specific tasks and knowledge discovery that leverages
the index files in a repository in addition to the base model of GitHub Copilot.
Figure 15.9 shows the main page of the client application with the navigation,
header, filters, products, login, and cart (see Figure 15.9).
This process involves a semantic search where the content of documents in the
indexed repository is analyzed, and the documents are then ranked by relevance.
GitHub Copilot Chat utilizes RAG to perform a similar semantic search, extract-
ing the most relevant snippets from these top-ranked documents. These snippets
are incorporated into the prompt, enabling GitHub Copilot Chat to generate an
accurate and relevant response.
This indexing process can vary greatly based on the size of the repository being
indexed. For small repositories, this can take seconds. For a larger repository
Chapter 15 ■ Exploring Copilot Business and Enterprise 265
like this one with a robust infrastructure including a client app and API, it will
take several minutes.
How Question
With multiple projects and different ways to run this example project, getting
started can be a hard task for new contributors. Let’s see how Copilot can assist
in gaining knowledge about the specific task we would like to accomplish.
As an example, submit the following request to Copilot:
How can I run the API locally?
After submitting this question to Copilot, you should get a response like the
one in Figure 15.11.
Figure 15.11: Copilot Chat response for how to run the API locally
266 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
This result is infused with the details from the indexed repository. There are
specifics on the type of database connections required, project-specific command-
line statements, and alternative dev containers using Docker.
Where Question
Next, let’s see how Copilot can give bespoke results for a specific part of the
repository. When you need to know where code is for a specific feature in a larger
repository, a simple symbolic or keyword search can leave you with limited
understanding. Let’s see how Copilot can supercharge your search experience
and give you the insights you need to be productive.
With a Copilot Chat window open and the repository selected as context for
the conversation, send a request to Copilot to understand where authentication
is handled (see Figure 15.12).
Here’s the Copilot request:
Where is authentication handled in our API?
Figure 15.12: Copilot Chat response for where authentication is handled in our API
Here Copilot surfaced important files related to our question. Unlike a tra-
ditional search, Copilot was able to provide additional context about what the
files do and specific attributes that pertain to the authentication question.
Chapter 15 ■ Exploring Copilot Business and Enterprise 267
As you can see, Copilot excels with the index that was created, enabling you
to get insights about your codebase with the power of Copilot to compile logical
responses and assets to help you do more.
specific domain of work involved in your software development life cycle (SDLC).
Here are some options that you might consider for your knowledge bases:
■■ Front-end development
■■ UI/UX design
■■ Front-end frameworks (React.js, Angular)
■■ Web technologies (HTML, CSS, JavaScript)
■■ Performance optimization
■■ Accessibility standards
■■ Cross-browser compatibility
■■ Backend development
■■ Programming languages (Python, Java, Node.js)
■■ Server and API development
■■ Security practices
■■ Scalability and performance
■■ Integration with third-party services
■■ Database administration
■■ Database management systems (MySQL, MongoDB)
■■ Data modeling and normalization
■■ Performance tuning
■■ Backup and recovery strategies
■■ Database security
■■ Quality assurance
■■ Testing techniques (unit, integration, system testing)
■■ Test automation
■■ Bug tracking and management
■■ Performance and load testing
■■ CI/CD integration
■■ Information assurance
■■ Risk management
■■ Compliance with security standards (ISO/IEC 27001, GDPR)
■■ Encryption and data protection
■■ Incident response
■■ Security policies and procedures
270 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
■■ Operations
■■ Monitoring and logging
■■ System administration
■■ Incident management
■■ Deployment and scaling
■■ Disaster recovery and business continuity
■■ Requirements management
■■ Requirements elicitation and documentation
■■ Change management
■■ Traceability of requirements
■■ Tools and software for managing requirements
These examples are intended to get you started. Make sure you consider
your organizational needs and team dynamics when implementing your
knowledge bases.
Let’s look at an example and focus on front-end development. Start by add-
ing a name and optional description. Then add relevant repositories to the
content area like dotnet/razor, twbs/bootstrap, and dotnet-architecture/
eShopOnWeb (see Figure 15.15).
After you have selected the repositories, you want for your knowledge base,
click Create at the bottom of the page.
You can now use the knowledge base from Copilot Chat in GitHub.com.
Open a new chat window and click the book icon at the bottom left of the chat
window (see Figure 15.16).
From here, click Frontend Development. As you can see, I created a second
knowledge base for backend development to showcase the menu structure.
Within the Copilot conversation, you will now see a “chatting with frontend
development” alert. This will direct Copilot to reference the repository Mark-
down files when answering questions in this conversation.
Since the front-end development knowledge base is referencing bootstrap,
ask Copilot what the latest version of that library is (see Figure 15.17).
What is the latest version of bootstrap?
You can see Copilot referenced six files to determine the best answer given
the question. Copilot responded with the correct, most current version of boot-
strap, which is 5.3.3 at the time of writing.
Let’s see what other information we can gather regarding version changes for
bootstrap. Ask Copilot what you have to change when migrating from version
4 to version 5 (see Figure 15.18).
272 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
Here you can see Copilot gathered great information on a migration from
version 4 to version 5 of bootstrap with references to the documentation from
the official repository.
Also, you might notice in Figure 15.18 that I have navigated to the boot-
strap repository and continued my conversation with Copilot. This ability to
follow your reference files linked in the chat responses while maintaining your
conversation with Copilot offers a great fluid experience. You can always mini-
mize the Copilot Chat window if you would like quick access while navigating
around different pages.
Summary
As you can see from this short example, this is applied across your entire orga-
nization to assist in productive conversations with up-to-date authoritative data
sources, which is a game-changer. These conversations can quickly uncover
company-specific information about internal libraries, tools, or best practices.
With knowledge bases, you and your team can quickly jump into con-
versations that give you the targeted and best information possible to keep
you moving.
With the specific question about files and a targeted feature within the repos-
itory, Copilot has done a great job of identifying the files used in this process.
With this result, open the Basket.cs class file.
Figure 15.19: Copilot Chat response for what files are used when updating a quantity for a
basket item
Figure 15.20: Copilot buttons and menus within a file in your codebase
Chapter 15 ■ Exploring Copilot Business and Enterprise 275
With the TotalItems property selected, select the Explain Menu option from
the inline Copilot menu. This will initiate a new conversation with Copilot with
an explanation of the selected code in the file (see Figure 15.21).
Copilot has given a great explanation of this single line of code, going in-depth
on the details of the property type, functions used, and purpose.
Figure 15.23: Copilot Chat response for improving basket item addition code
Chapter 15 ■ Exploring Copilot Business and Enterprise 277
With the Basket.cs file attached to the chat window, you can have a
conversation with Copilot that will be infused with context from the attached
file. With the attachment, you can make requests to Copilot that have a more
simplistic structure, as shown in Figure 15.25.
Explain the purpose of this file.
Here you can see that Copilot understands the context of your question and
can give you an insightful response with limited work on your behalf.
In addition to a single file attachment, you can click the paperclip icon to
select as many files as you need to support your conversation with Copilot
(see Figure 15.26).
278 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
Figure 15.26: Copilot Chat window attachment search for files and symbols
Chapter 15 ■ Exploring Copilot Business and Enterprise 279
Figure 15.27: Web application basket page to be modified with a remove button
280 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
Here you can see that the basket page allows users to see their items selected,
as well as the title, price, quantity, and cost. The user can continue shopping,
update the quantity for an item, or check out.
Currently, a user needs to reduce the quantity of a basket item to zero and
click Update to remove an item. To improve this user experience, we will add
a remove button to the basket page for each item to give an intuitive way for
the user to interact with the basket item.
Figure 15.28: Copilot Chat response for how to add a remove item feature to the basket page
Copilot has responded with reference to the repository. At the top of the
response, you can see that Copilot uses a search term “remove item from bas-
ket” against the indexed repository information to gather all of the necessary
resources to give a holistic response to our request.
Chapter 15 ■ Exploring Copilot Business and Enterprise 281
In summary, here are the steps Copilot has outlined for our change:
1. Update the Basket domain model.
2. Update the BasketService and BasketViewModelService to expose the
functionality to the web application layer.
3. Update the basket page (Index.cshtml and Index.cshtml.cs)
Open a second terminal at the project root and execute the following to run
the client application:
cd src/Web
dotnet watch
With the API and web projects running in watch mode, you can now make
the edits outlined in the previous section.
Copilot for a code completion via an inline comment, start a new chat within
VS Code, or use Copilot Chat in GitHub.com, you should end up with a function
like this added to your Basket.cs file:
public void RemoveItem(int catalogItemId)
{
_items.RemoveAll(i => i.CatalogItemId == catalogItemId);
}
After adding this code to your Basket.cs file, you can then add a test using
Copilot Chat to ensure the functionality. Do this by selecting the RemoveItem()
function in the editor. Open a new chat with Copilot in the side menu. From
this chat, send a request to Copilot like this (see Figure 15.29):
@workspace /tests #selection #file:BasketAddItem.cs XUnit
Figure 15.29: Copilot Chat response for creating tests for the new method
Next, with the IBasketService.cs file open for context, open the Basket
Service.cs file and go to the bottom of the file. Since you have a context of the
interface file, Copilot should be able to discern your intent when adding new
lines to the bottom of the class. If not, you can add an inline comment to drive
the code suggestion from Copilot (see Figure 15.30).
Figure 15.30: Copilot function creation for remove item from basket function
Here you can see Copilot creating the function with the necessary interactions
with the basket specification class, basket repository, and basket class with the
assistance of the interface file context. Here is the complete method for reference:
public async Task<Result<Basket>> RemoveItemFromBasket(int basketId,
string username, int catalogItemId)
284 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
{
var basketSpec = new BasketWithItemsSpecification(basketId);
var basket = await _basketRepository.FirstOrDefaultAsync
(basketSpec);
if (basket == null) return Result<Basket>.NotFound();
basket.RemoveItem(catalogItemId);
await _basketRepository.UpdateAsync(basket);
return basket;
}
With this function in place, which can use the new basket service Remove
ItemFromBasket function, you will also need to adjust the Index.cshtml page.
For my edit, I added a btn btn-link button to the right of the other basket
item table row fields. Additionally, I adjusted some alignment of the grid rows
to be aligned with the new remove button. Here is a snippet of the button that
was added to the cshtml file:
<section class="esh-basket-item esh-basket-item--middle col-xs-1">
<button class="btn btn- link" name="removebutton" asp- route- id="@
item.CatalogItemId" type="submit" asp-page-handler="Remove">
Remove
</button>
</section>
With all these changes in place, the remove button is now functioning. The
output you should have after making the edits for layout and adding the button
as described earlier should look like Figure 15.31.
Chapter 15 ■ Exploring Copilot Business and Enterprise 285
Figure 15.31: Basket page with new remove button for each item
With the remove button in place and functioning, you are ready to commit
to the local branch and submit the pull request.
NOTE The GitHub Copilot generate commit message feature is available to all
GitHub Copilot plans.
286 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
Managing Access
In the Copilot menu in your organization settings, select the Access menu item.
This will enable you to see your Copilot seat count, estimated monthly cost,
access control settings for your organization, and a list of all individuals with
access (see Figure 15.35).
As you can see from Figure 15.35, you can enable, disable, or enable settings
for selected members. Once you have selected an option, you can add seats via
a search utility. This feature allows you to select teams or individual organiza-
tion members.
Managing Policies
The next option you can manage is the policies for GitHub Copilot, encompass-
ing the following:
■■ Suggestions matching public code
■■ Copilot in GitHub.com
■■ Copilot Chat in the IDE
■■ Copilot in the CLI
Figure 15.36 shows a view of this page as an organization member with the
settings and their indicators of enabled and disabled status.
Controlling these settings enables you to roll out Copilot in your organization
in a thoughtful and strategic way.
290 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
At the enterprise level, policies may be centrally established for the entire
enterprise, or alternatively, the decision-making authority may be delegated to
the owners of individual organizations to tailor the policy as appropriate for
their specific contexts.
Content Exclusion
Content exclusions can be set to ensure you don’t expose sensitive information.
Currently, these exclusions only affect code completions and do not affect Copilot
Chat. Additionally, Copilot will prevent directly accessing excluded files and
folders that you specify (see Figure 15.37).
For more information on the allowable syntax and more examples, head to
the official documentation at the following URL:
https://docs.github.com/copilot/managing-github-copilot-in-your-
organization/configuring-content-exclusions-for-github-copilot
Here you can see the audit logs with a filter for action:copilot, which allows
you to see all Copilot activity against the organization settings.
292 Part IV ■ Key Insights and Advanced Use Cases for GitHub Copilot
Looking Ahead
Today, Copilot Enterprise provides the tools you need to be much more pro-
ductive and empowered in the SDLC. GitHub is moving at a rapid pace to
enhance the developer experience across a wide spectrum of developer tooling
and services. The following sections are development areas that are of interest
for the 2024 calendar year.
These product features might change or might not be released after their alpha
and beta testing rounds. Regardless, there are some very compelling features
on the horizon, and I’d like to share them with you.
Conclusion
This chapter provided a comprehensive overview of GitHub Copilot’s capabil-
ities for Copilot Business and Copilot Enterprise applications. It began with an
introduction to Copilot’s functionalities on GitHub.com and progressed through
advanced features like retrieval augmented generation and the benefits of
indexing code repositories to enhance Copilot’s understanding.
The use of Copilot Chat within code repository files and its application in
enhancing pull requests were highlighted as methods to streamline development
processes and improve collaboration. Strategies for managing GitHub Copilot
effectively were also discussed, along with a look toward future advancements
in the tool.
The insights from this chapter should equip you to assess and integrate
AI-powered tools like GitHub Copilot within your organization’s SDLC
addressing both the potential and the challenges of increased AI adoption in
professional workflows.
References
As this exploration of GitHub Copilot concludes, it’s clear that the landscape
of software development is undergoing a significant transformation. GitHub
Copilot has introduced a new paradigm of programming, one where
artificial intelligence acts not just as a tool but as a collaborator, enhancing
software development capabilities and workflows far beyond traditional
developer tooling.
Throughout this book, you have encountered many aspects of GitHub
Copilot, from basic code completions to its role in learning new program-
ming languages, writing robust tests, refactoring code, and even navigating
the complexities of CI/CD processes. You’ve seen how Copilot can act as a
universal converter, diagnose and resolve bugs, and help ensure code security.
As technology evolves, so will GitHub Copilot, and with it, its applications
in the software development life cycle (SDLC) will continue to expand. Future
advancements will drive deeper integration of AI tools in the SDLC, potentially
reshaping job roles and industry standards. Embracing these tools can lead to
unprecedented productivity and innovation.
Encouraging responsible use of AI and understanding its implications on
privacy, security, and employment are essential as you move forward. As you
integrate GitHub Copilot into your development practices, please continue to
295
296 Conclusion
engage with the community, share insights, and contribute to the progression
of this transformative tool.
Thank you for joining me on this educational journey through the features,
capabilities, and applications of GitHub Copilot. The knowledge and strategies
shared here will help you harness the full potential of GitHub Copilot in your
development workflow.
APPENDIX
This appendix is a curated list of resources designed to help you understand and
navigate the various aspects of GitHub Copilot. This guide includes everything
from getting started with the tool to detailed information about subscription
plans, community support, and legal guidelines. Whether you are a new user
looking to integrate GitHub Copilot into your workflow or seeking deeper
insights into its impact and ethical considerations, these resources provide
valuable information to enhance your knowledge and use of this innovative tool.
■■ GitHub Copilot Overview and Subscription Plans
■■ Community Engagement and Support
■■ Legal and Ethical Considerations
297
298 Appendix ■ Resources for Further Learning
OpenAI Codex
Get an introduction to Codex, the AI model behind GitHub Copilot, which
is capable of interpreting and executing commands in several programming
languages.
https://openai.com/blog/openai-codex
Glossary
303
304 Glossary
Dockerfile — A text document that contains all the commands a user could
call on the command line to assemble an image. Docker can build images
automatically by reading the instructions from a Dockerfile.
dotnet CLI — The command-line interface for .NET used to create, run,
and manage .NET applications from the command line or terminal.
#editor context variable — A tag used in prompts to give GitHub Copilot
context about the visible code in the editor window, aiding in relevant
and accurate code suggestions.
end-to-end tests — Comprehensive testing that validates every process
along with the flow of an application from start to finish. It ensures the sys-
tem’s components function together as expected from the user’s perspective.
Entity Framework — An open-source object-relational mapping frame-
work that is part of the .NET Framework.
ESLint — A pluggable and configurable linter tool for identifying and
reporting on patterns in JavaScript, helping to make code more consistent
and avoiding bugs.
EU AI Act — European Union legislation aimed at regulating AI appli-
cations by setting standards for ethical practices, risk assessment, and
compliance for AI systems used within the EU.
/explain command — A command used in Copilot Chat to request detailed
explanations or discussions about specific pieces of code or concepts.
#file context variable — A tag that allows users to specify which file(s)
should be considered by GitHub Copilot during the conversation, even
if the file is not currently open.
FIPS (Federal Information Processing Standards) — Publicly announced
standards developed by the United States federal government for use in
computer systems.
/fix command — A command in Copilot Chat where GitHub Copilot pro-
vides suggestions to correct errors in code based on the context of the error.
Gartner Hype Cycle — A methodology used by Gartner, an IT research
and advisory firm, to represent the maturity, adoption, and social appli-
cation of specific technologies.
generative AI models — Artificial intelligence models that can generate
new content based on their training data.
Gherkin syntax — A business readable, domain-specific language that lets
you describe software’s behavior without detailing how that behavior is
implemented. Gherkin is primarily used to write structured tests for BDD.
GitHub — A platform for version control and collaboration, allowing
developers to work together on projects from anywhere.
306 Glossary
311
312 Index ■ B–C
Neovim privacy
defined, 307 about, 18–20, 221
enhancing, 176–180 data protection, 221–222
NestJS, 88, 95, 101, 102, 115, 135, 307 vulnerability prevention system, 222–223
.NET, 307 Process-Specific AI Integration, in level 2, AI
.NET Core SDK, 71, 307 integration in SDLC, 235
/new command, 61–62, 74, 307 product backlog, 242
/newNotebook command, 62–63, 308 product backlog refinement (PBR) meeting, 242
NIST (National Institute of Standards and programming
Technology), 19, 308 with Copilot in IDE, 254
No AI-Driven Optimization, in level 0, AI questions about, 260–262
integration in SDLC, 234 with responsible AI, 226
Node.js, 9, 102, 115, 135, 177, 308 programming languages
nondeterministic nature, of GitHub Copilot, 13 about, 69–70
nontyped languages, enhancing with adding code, 78–79
types, 196–198 basics of, 72–74
nvim command, 177 creating console applications, 74–77
explaining code with Copilot, 77–78
learning to test, 79–85
O
setting up development environment, 70–72
Objective-C, 203–205
translating natural language to, 188–189
object-oriented languages, converting, 203–205
project documentation, 130–132
obtaining license for GitHub Copilot, 4–5
prompt engineering
Open Completions Panel action, 40
defined, 308
Open Tabs context, 50
defining with Copilot Chat, 48–52
Open Web Application Security Project
prompts, 19
(OWASP), 133–134, 308
pull requests
OpenAI, 18
enhancing, 279–287
OpenAI Codex, 18, 301, 308
summarizing, 286–287
operations, 270
Organization-wide AI Integration, in level 3, AI
integration in SDLC, 236 Q
OWASP Top 10, 308 :q command, 177
quality assurance, 269
querying, 170
P
questions, repository-specific, 265–267
pair programming, 308
Quick chat, 47–48
Pandas, 199–201, 308
Panel (GitHub Copilot), 34, 35
password hashing, 140–141 R
PBR (product backlog refinement) RAG (retrieval-augmented generation),
meeting, 242 263–264, 300, 308
Performance Benchmarking, in level 4, AI Reactive Problem-Solving, in level 0, AI
integration in SDLC, 237 integration in SDLC, 234
Performance Measurement, in level 2, AI React.js, 308
integration in SDLC, 235 red teaming, 220–221, 308
planning, with Copilot, 243–245 referencing open tabs, 32–33
Polars, 199–201, 308 refining backlog, 242–243
policies, managing, 289–290 reliability, 220–221
Postgre SQL, 205–206 remove() function, 118
PowerShell RemoveItem() function, 281–282
Neovim on Windows via, 177 requirements gathering, 239–241
setting up aliases for Copilot, 185 requirements management, 270
Vim on Windows via, 177 Requirements phase, in SDLC, 230
Predictive Analytics for Process Optimization, research and insights, 300–301
in level 4, AI integration in SDLC, 237 researching responsible AI principles, 226
prerequisites, for testing Copilot, 10 resolving
Index ■ R–T 317