Top tips for efficient AI-powered Code Suggestions with GitLab Duo

1 week ago 7
News Banner

Looking for an Interim or Fractional CTO to support your business?

Read more

GitLab Duo, our suite of AI-powered features, provides a unique opportunity to make your DevSecOps workflows more efficient. To make the most of GitLab Duo requires hands-on practice and learning in public together. This tutorial centers on GitLab Duo Code Suggestions and provides tips and tricks, learned best practices, and some hidden gems (including how to pair Code Suggestions with our other AI features for even more efficiency). You'll also discover how AI greatly improves the developer experience.

The best practices, tips, and examples in this article have been created from scratch and are included in the GitLab Duo documentation and GitLab Duo prompts project, maintained by the GitLab Developer Relations team. Bookmark this page, and navigate into the respective chapters at your convenience.

What you'll learn:

  1. Why use GitLab Duo Code Suggestions?
  2. Start simple, refine prompts
  3. Practice, practice, practice
  4. Re-trigger Code Suggestions
  5. Code Suggestions vs, code generation
  6. Take advantage of all GitLab Duo features
  7. More tips
  8. Share your feedback

Why use GitLab Duo Code Suggestions?

Consider these two scenarios:

  1. As a senior developer, you have the confidence in your ability with various programming languages to write new source code, review existing code, design resilient architectures, and implement new projects. However, getting familiar with the latest programming language features requires time, research, and a change of habits. So how can you quickly learn about new language feature additions that could make your code even more robust or use resources more sustainably?

    • As a personal example, I learned the C++03 standard, later C++11 and never really touched base on C++14/17/20/23 standards. Additionally, new languages such as Rust came around and offered better developer experiences. What now?
  2. As a new engineer, it can be challenging to navigate new projects, get familiar with a new programming language, understand specific algorithms, and find the documentation for structures, interfaces, and other technical components. New engineers are also learning under pressure, which often leads to errors and roadblocks along the way. There is no time for digging into best practices.

    • I, myself, never really learned frontend engineering, just some self-taught HTML, CSS, and JavaScript. Adapting into frontend frameworks such as VueJS after a decade feels overwhelming, and I have little time to learn.

These scenarios show how hard it can be to keep up with the latest programming languages, best practices, and other key information. GitLab Duo Code Suggestions, which predictively completes code blocks, defines function logic, generates tests, and proposes common code like regex patterns – all in your coding environment. Code Suggestions provides the AI assistance necessary to learn what you need to know while staying in your development flow.

Live demo! Discover the future of AI-driven software development with our GitLab 17 virtual launch event. Register today!

Start simple, refine prompts

My own GitLab Duo adoption journey started with single-line code comments, leading to not-so-great results at first.

# Generate a webserver // Create a database backend /* Use multi-threaded data access here */

After experimenting with different contexts, and writing styles, I found that code generation out of refined comments worked better.

# Generate a webserver, using the Flask framework. Implement the / URL endpoint with example output. // Create a database backend. Abstract data handlers and SQL queries into function calls. /* Use multi-threaded data access here. Create a shared locked resource, and focus on supporting Linux pthreads. */

Code comments alone won't do the trick, though. Let's explore more best practices.

Practice, practice, practice

Find use cases and challenges for your daily workflows, and exclusively use GitLab Duo. It can be tempting to open browser search tabs, but you can also solve the challenge in your IDE by using GitLab Duo. Here are some examples:

  1. Fix missing dependencies (which always cause build/execution failures).
  2. If you're missing logging context, let Code Suggestions auto-complete started function calls, including print statements.
  3. Generate common methods and attributes for object-oriented design patterns (e.g. getter/setter methods, toString() and object comparison operators, object inheritance, etc.).
  4. Identify the function that generates random crashes. Use Code Suggestions to implement a new function with a different algorithm.
  5. If you encounter application cannot be compiled or executed, cryptic error, ask GitLab Duo Chat about it.
  6. Learn about existing (legacy) code, and strategies to document and refactor code into modern libraries. Start a v2 of an application with a new framework or programming language, helping solve technical debt.
  7. Prevent operations and security issues in Git history by detecting them before they occur (e.g. performance, crashes, security vulnerabilities).

Think of the most boring - or most hated - coding task, and add it to the list above. My least favorite tasks are attribute getter/setter methods in C++ classes (as can be seen in the video below), immediately followed by regular expressions for email address format.

<!-- blank line --> <figure class="video_container"> <iframe src="https://www.youtube.com/embed/Z9EJh0J9358?si=QGvQ6mXxPPz4WpM0" frameborder="0" allowfullscreen="true"> </iframe> </figure> <!-- blank line -->

It can also help to use Code Suggestions in different programming languages, for example focusing on backend and frontend languages. If you are experienced in many languages, take a look into languages that you have not used in a while, or look into learning a new programming language such as Python or Rust.

When you adopt Code Suggestions into a fast auto-completion workflow, it can happen without any interruption. The suggested code is greyed out and optional, depending on the user interface – for example, VS Code. This means that it will not distract you from continuing to write source code. Try using Code Suggestions on your own by familiarizing yourself with how suggestions are shown, how you can fully or partially accept them, and soon they will become optional help to write better code.

Image with code suggestions greyed out

Fix missing dependencies

After building or running source code, missing dependency errors might be logged and prevent further execution and testing. The following example in Go shows an error from go build, where the source code did not import any dependencies yet. A manual approach can be collecting all listed dependencies, running a unique sort on them, and adding them into the source code file, as shown below.

Go build failed - missing dependencies

But what if GitLab Duo knows about the file context and missing dependencies already? Navigate into the top section and add a comment, saying // add missing imports and wait for Code Suggestions.

GitLab Duo Code Suggestions - go build failed missing dependencies suggested fix

Running go build again results in success, and the source code can be tested and run.

Go build failed - missing dependencies fixed

Boilerplate code: Optimized logging

Q: Logging – and more observability data with metrics and traces – can be hard and tedious to implement. What is the most efficient way to implement them that does not impact the application performance or cause bugs?

A: Use Code Suggestions to generate logging function calls, and refactor the code into robust observability instrumentation library abstractions. This method can help to prepare the code for later integration with OpenTelemetry, for example.

Example for a logging class in Ruby:

# Create Logging utility class # Define default log level as attribute # Add method for logging, inputs: level, app, message # Print the data with formatted date and time in syslog format # Potential AI-generated code below class Logging attr_accessor :log_level def log(level, app, message) time = Time.now.strftime("%b %d %H:%M:%S") puts "#{time} #{app}[#{Process.pid}]: #{level} - #{message}" end end # Instantiate class and test the log method # Potential AI-generated code below logger = Logging.new logger.log_level = :debug logger.log(:info, 'MyApp', 'Application started - info') logger.log(:debug, 'MyApp', 'Application started - debug') logger.log(:error, 'MyApp', 'Application started - error') logger.log(:fatal, 'MyApp', 'Application started - fatal') logger.log(:warn, 'MyApp', 'Application started - warn')

Utility helper functions, well tested

Q: The programming language does not provide basic functions in the standard library. I'm tempted to open my browser to add string manipulation and regular expression parser functions.

A: Create a new file called utility.{language-suffix} and add a code comment on top. Instruct Code Suggestions to generate a string manipulation function ().

Example for a string manipulation method in Python:

# Create a function to search for a string in a string, return the index # Optionally remove search string, and return modified string # Test the function on the string "Cool programming languages: C++, Rust, Python" - Remove the string "C++" # Potential AI-generated code below def search_and_remove(text, search): index = text.find(search) if index != -1: return index, text[:index] + text[index+len(search):] else: return None, text text = "Cool programming languages: C++, Rust, Python" index, new_text = search_and_remove(text, "C++") print(index, new_text)

Async exercise: Ask GitLab Duo Chat how to add tests in Python, select the source code, and use the /tests slash command.

A similar example can be implemented in Go, creating utility functions for unique integer values in an array, or the sum of all even values. Start with defining the project structure through go mod init gitlab.com/group/project and create the array.go file. Define the package and start with the first code comment to generate the functions.

package array // Create a function that returns unique values from an integer array // Possible AI-generated code func unique(ints []int) []int { occurred := map[int]bool{} result := []int{} for _, i := range ints { if !occurred[i] { occurred[i] = true result = append(result, i) } } return result } // Create a function that returns the sum of all even numbers in an integer array // Possible AI-generated code func sumEvens(ints []int) int { var sum int for _, i := range ints { if i%2 == 0 { sum += i } } return sum }

Async exercise: Create more utility helper functions in dedicated libraries, and use Chat to select and generate /tests. For the Go example, you can inspect potential solutions in the go/utility/array_test.go file in the GitLab Duo Prompts project. Build and test the code using go build && go test.

Generate regular expressions

Developers' favorite one liners, never touched again. git blame knows very well but might not be able to provide enough context. GitLab Duo can help with regular expressions creation, explanation, and refactoring, in the following example:

Q: My regular expressions for parsing IPv6 and IPv4 addresses do not work. What's the best approach to solve this?

A: Use Code Suggestions comments to generate examples using these regex types. Combine the questions with Chat, and ask for more examples in different languages. You can also select the existing source, and use a refined prompt with /refactor using regular expressions in the Chat prompt.

Async exercise: Choose your favorite language, create a function stub that checks IPv6 and IPv4 address strings for their valid format. Trigger Code Suggestions to generate a parsing regular expression code for you. Optionally, ask Chat how to refine and refactor the regex for greater performance.

I chose TypeScript, a language on my personal learning list for 2024: // Generate a TypeScript function which parses IPv6 and IPv4 address formats. Use regular expressions.

Code Suggestions - typescript utility parse ip address regex

Code Suggestions typescript - utility parse ip address regex tests

Re-trigger Code Suggestions

You can trigger Code Suggestions by pressing the enter or space key, depending on the context. In VS Code and the GitLab Web IDE, the GitLab Duo icon will appear in the same line, and at the bottom of the window.

If you accepted a suggestion, but actually want to try a different suggestion path, select the code, delete the line(s) and start over.

Tip: Different keystrokes and strategies for Code Suggestions are recorded in this video:

<!-- blank line --> <figure class="video_container"> <iframe src="https://www.youtube.com/embed/ORpRqp-A9hQ?si=CmA7PBJ9ckWsvjO3" frameborder="0" allowfullscreen="true"> </iframe> </figure> <!-- blank line -->

Common keyboard combinations to re-trigger Code Suggestions

Especially in the early adoption phase of Code Suggestions, you'll need to practice to get the best results from comments, existing code style, etc., put into context.

A common keystroke pattern for triggering suggestions can be

  1. Press Enter and wait for the suggestion.
  2. Press Space followed by Backspace to immediately delete the whitespace again, or
  3. Press Enter to re-trigger the suggestion. Backspace to delete any leftover new lines.

When a suggestion makes sense, or you want to see how far you can get:

  1. Continue pressing Tab to accept the suggestion.
  2. Add a space or press Enter to open a new scope for triggering a new suggestion.
  3. Continue accepting suggestions with Tab.

Note that generative AI sometimes ends up in a loop of suggesting similar code paths over and over again. You can trigger this behavior by inserting test data into an array, using strings and numbers in a sorted order or by generating different API endpoints, as it tries to guess which other endpoints could be helpful. When this happens, break the acceptance flow, and continue writing code as normal.

Stuck in the middle of suggestions

Sometimes, the code suggestions may stop in the middle of a variable, function, etc. definition. If you are unsure about the syntax, or want to restart the code suggestions:

  1. Delete the last character(s) or the entire line, using Backspace.
  2. Alternatively, use shift cursor left (select characters) or cmd shift cursor left (select entire line), followed by Backspace.
  3. Move the cursor into the line above, and press Enter to force a Code Suggestions trigger again.

Code Suggestions stopped

When Code Suggestions stops, there can be multiple reasons:

  1. The current file scope ends – for example, a main() function has been generated and closed.
  2. There could be connection problems to the GitLab instance (self-managed) or GitLab.com (SaaS, Dedicated). Follow the troubleshooting documentation.

Code suggestions vs. code generation

Code suggestions "come as you go" while writing code, and help with completing line(s). Code generation on the other hand requires more context to create entire code blocks, consisting of functions, algorithms, classes, etc.

The following sections discuss both methods, and how to get started with a practical example.

Code suggestions flow with comments

Use your natural programming flow, and stop to adapt to adding code comments when helpful for context and better suggestions. You can accept code suggestions using the Tab key, or selectively accept words using the cmd cursor right keyboard shortcut.

The following new challenge implements a simple Linux statistics tool in C, mimicking the functionality of iostat, vmstat and du CLI commands on Linux. Sometimes, these low-level metrics come in handy for presenting application metrics, or otherwise help with debugging when requesting support data from customers.

Create a new application directory called linux_stat and main.c file, and let Code Suggestions complete everything else. First, start with a simple code comment block:

// Create a Linux statistic tool // Collect IO, performance, disk usage, TCP latency // Print summaries

Next, press Enter to trigger the creation of the main() method. If not automatically created, force it through a new code comment.

// Create main function to collect data

In my attempts, generative AI did not immediately implement all functionality. Instead, it added a TODO comment into the following code block.

int main() { struct stat statbuf; if (stat("/etc", &statbuf) != 0) { perror("stat"); return 1; } printf("IO Block Size: %ld\n", statbuf.st_blksize); // TODO: add CPU usage, disk usage, network latency measurements return 0; }

Move the cursor after the TODO comment, and continue with a new comment to collect CPU usage:

// Collect CPU usage // Example for AI-generated code below double cpu_usage; FILE* stat_file = fopen("/proc/stat", "r"); if (stat_file == NULL) { perror("fopen"); return 1; } // Parse /proc/stat to get CPU usage fscanf(stat_file, "cpu %lf", &cpu_usage); printf("CPU Usage: %.2f%%\n", cpu_usage * 100); fclose(stat_file);

The generated code might not be 100% accurate, since measuring CPU usage on Linux requires taking samples over a defined time range. Thus, the caller needs to calculate the real CPU utilization from all values in /proc/stat, including system, nice, user, idle, iowait, etc..

Async challenge: Optimize the collection process with average calculation.

Repeat the steps for disk usage and network latency. The code comment is written by you, the C source code is generated with GitLab Duo.

// Collect disk usage // Collect network latency // Example for AI-generated code below int sockfd = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in servaddr; servaddr.sin_family = AF_INET; servaddr.sin_port = htons(80); inet_pton(AF_INET, "8.8.8.8", &servaddr.sin_addr);

The generated code may use public IP addresses to test network latency. Change the IPv4 address to GitLab.com's current address.

inet_pton(AF_INET, "172.65.251.78", &servaddr.sin_addr);

The generated source code added more header dependencies. Navigate into the top section of the file, and add a comment to include all required headers:

// Import required headers

Build and run the application on Linux, example on Ubuntu 22 LTS:

# Install compiler apt install gcc # Build gcc main.c -o linux_stat # Build: If the math.h header is included, linking against the library is needed, too gcc linux_stat.c -o linux_stat -lm # Run the tool ./linux_stat

Bonus: Change the code to use IPv6, and check the GitLab.com IPv6 address again (dig gitlab.com AAAA +short).

// Collect network latency // Use IPv6 // Example for AI-generated code below struct sockaddr_in6 servaddr; servaddr.sin6_family = AF_INET6; servaddr.sin6_port = htons(80); //inet_pton(AF_INET6, "2001:db8::1", &servaddr.sin6_addr); inet_pton(AF_INET6, "2606:4700:90:0:f22e:fbec:5bed:a9b9", &servaddr.sin6_addr); int sockfd = socket(AF_INET6, SOCK_STREAM, 0);

C Linux stat tests

The full working source code is available in the GitLab Duo Prompts project in the directory for C code.

Async exercise: Refactor the C code into Rust, using only GitLab Duo. Start by selecting the source code, and use the Duo Chat prompt /refactor into Rust.

Tip: Thoughtful code comments make the source code more readable, too. This helps new team members with onboarding, site reliability engineers with debugging production incidents, and open source contributors with merging their first MRs.

Start with a comment on top for code generation

Source code can be organized in multiple files. Whether you start with a new application architecture, or refactor existing source code, you can take advantage of code generation with GitLab Duo.

Start with a comment block on top, and make it a step-by-step description. You can also break longer comments into multiple lines, revisiting the examples in this article. This pattern also helps to think about the requirements, and can help refining the prompts.

# Generate a webserver, using the Flask framework. # Implement the / URL endpoint with example output. +# Add an endpoint for Promtheus metrics // Create a database backend. // Abstract data handlers and SQL queries into function calls. +// Use PostgreSQL as default backend, and SQLite for developers as fallback. /* Use multi-threaded data access here. Create a shared locked resource, and focus on supporting Linux pthreads. +Abstract the thread creation/wait procedures into object-oriented classes and methods. */

More code generation prompts for supported programming languages are available in the GitLab Duo Use Cases documentation.

Intent detection for code suggestions and generation

Code Suggestions, depending on the GitLab Language Server in your IDE, will parse and detect the intent and offer code completion suggestions in the same line or code generation.

The technology in the background uses TreeSitter to parse the code into an AST, and determine whether the scope is inside a code comment block (generation), or inside the source code (completion). This detection needs to be executed fast on the client IDE, and proves to be a great use case for WebAssembly. You can learn more in this epic, and the following video, which provides a look into the GitLab Language Server powering Code Suggestions:

<!-- blank line --> <figure class="video_container"> <iframe src="https://www.youtube.com/embed/VQlWz6GZhrs" frameborder="0" allowfullscreen="true"> </iframe> </figure> <!-- blank line -->

Tell a story for efficient code generation

Code generation is art. Tell the story, and AI-powered GitLab Duo can assist you.

The following example aims to implement an in-memory key-value store in Go, similar to Redis. Start with a description comment, and trigger Code Suggestions by continuing with a new line and pressing Enter.

// Create an in-memory key value store, similar to Redis // Provide methods to // set/unset keys // update values // list/print with filters

We can be more specific – which methods are required for data manipulation? Instruct Code Suggestions to generate methods for setting keys, updating values, and listing all contained data.

// Create an in-memory key value store, similar to Redis // Provide methods to // set/unset keys // update values // list/print with filters

Accept all suggestions using the Tab key. As a next step, instruct Code Suggestions to create a main function with test code.

// Create a main function and show how the code works

If the test data is not enough, refine the generated code with a focus on extreme test cases.

Tip: You can use the same method for refined Chat prompts and test generation, /tests focus on extreme test cases.

// Add more random test data, focus on extreme test cases

Code Suggestions - go kv more test data

The full example, including fixed dependencies, is located in the gitlab-duo-prompts project in the code-suggestions/go/key-value-store directory. Update the main.go file, and build and run the code using the following command:

go build ./key-value-store

The first iteration was to create a standalone binary and test different implementation strategies for key-value stores. Commit the working code and continue with your GitLab Duo adoption journey in the next step.

Tip: New projects can benefit from Code Generation, and require practice and more advanced techniques to use code comments for prompt engineering. This method can also make experienced development workflows more efficient. Proof of concepts, new library introductions, or otherwise fresh iterations might not always be possible in the existing project and framework. Experienced developers seek to create temporary projects, and isolate or scope down the functionality. For example, introducing a database backend layer, and benchmarking it for production performance. Or, a library causing security vulnerabilities or license incompatibilities should be replaced with a different library, or embedded code functionality.

Iterate faster with code generation

Experienced developers will say, "There must be a key-value library in Go, let us not reinvent the wheel." Fortunately, Go is a mature language with a rich ecosystem, and awesome-go collection projects, for example avelino/awesome-go, provide plenty of example libraries. Note: This possibility might not be the case for other programming languages, and requires a case-by-case review.

We can also ask GitLab Duo Chat first, Which Go libraries can I use for key-value storage?:

Chat - ask golang libraries kv

And then refine the Code Suggestions prompt to specifically use the suggested libraries, for example, BoltDB.

// Create an in-memory key value store, similar to Redis // Provide methods to // set/unset keys // update values // list/print with filters +// Use BoltDB as external library

Repeat the pattern from above: Generate the source code functions, then ask GitLab Duo to create a main function with test data, and build the code. The main difference is external libraries, which need to be pulled with the go get command first.

go get go build

If the source code build fails with missing dependencies such as fmt, practice using GitLab Duo again: Move the cursor into the import statement, and wait for the suggestion to add the missing dependencies. Alternatively, add a comment saying Import all libraries.

Code Suggestions - go kv external lib boltdb fix dependencies

You can also add more test data again, and verify how the functions behave: // Add more random test data, focus on extreme test cases. In the following example, an empty key causes the program to panic.

Code Suggestions - Go kv external lib boltdb test extreme cases panic

This example is a great preparation for test cases later on.

Practical code generation: Cloud-native observability

Think of a client application in Go, which lists the current state of containers, pods, and services in a Kubernetes cluster, similar to the kubectl get pods command line. The Kubernetes project provides Go libraries to programmatically interact with the Kubernetes APIs, interfaces, and object structures.

Open your IDE, and create a new Go project.

Tip: You can ask Chat how to do it - How to start a Go project? Please show CLI command examples.

Start with a single comment on top of the main.go file, and describe the application purpose: Observability in Kubernetes.

// Create a client for Kubernetes observability

Think about the main requirements: Get access to Kubernetes, create context, namespace, and inspect the state. Additionally, instruct Code Suggestions to import packages and create a main package in the main.go file.

First iteration:

// Create a client for Kubernetes observability // Inspect container, pod, service status and print an overview

This might do unexpected things with hardcoding the access credentials, missing contexts, failing builds.

Second iteration:

// Create a client for Kubernetes observability // Create a function that // Read the kubernetes configuration file from the KUBECONFIG env var // Inspect container, pod, service status and print an overview

This might not know about Kubernetes contexts and namespaces, thus leading to build errors or unexpected results.

Third iteration:

// Create a client for Kubernetes observability // Create a function that // Read the kubernetes configuration file from the KUBECONFIG env var // Create kubernetes context, namespace default // Inspect container, pod, service status and print an overview

This example hardcodes the Kubernetes context and default namespace to generate an initial foundation. Later iterations can read the namespace value from a command line parameter, or configuration file.

The final example can look like the following. In addition to the application functionality, it also instructs Code Suggestions to import all dependencies, and create a main package in main.go.

// Create a client for Kubernetes observability // Create a function that // Read the kubernetes configuration file from the KUBECONFIG env var // Create kubernetes context, namespace default // Inspect container, pod, service status and print an overview // Import necessary packages // Create main package

<details> Solution <summary>

package main import ( "context" "fmt" "os" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func main() { kubeconfig := os.Getenv("KUBECONFIG") config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) if err != nil { panic(err) } clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err) } pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{}) if err != nil { panic(err) } fmt.Printf("There are %d pods in the cluster\n", len(pods.Items)) // Additional code to inspect services, containers, etc }

</summary> </details>

Example output:

duo code suggestions - go k8s o11y output

Async exercise: Complete the project with code for inspecting services, containers, etc., and export the findings to OpenTelemetry.

Tip: Practice with the GitLab Duo use cases: Code generation prompts in the documentation, and/or send merge requests with your working prompts.

While recording a short video to highlight how code generation is working, another more refined source code was generated. You can inspect the differences in this commit, and benefit from both solutions.

<!-- blank line --> <figure class="video_container"> <iframe src="https://www.youtube.com/embed/ORpRqp-A9hQ" frameborder="0" allowfullscreen="true"> </iframe> </figure> <!-- blank line -->

Take advantage of all GitLab Duo features

Combine Chat with Code Suggestions

In combination with GitLab Duo Chat, Code Suggestions becomes even more powerful. The following workflow illustrates the intersection of AI efficiency:

Write and generate new code using Code Suggestions. The source code will be verified through CI/CD automation, code quality tests, and security scanning. But what about the developer's knowledge?

  1. In your IDE, select the generated code portions and use the /explain slash command in the Chat prompt. You can even refine the prompt to /explain with focus on algorithms, or otherwise helpful scopes such as potential security or performance problems, etc.

    • Continue writing and maintaining source code, but at some point code quality decreases and refactoring gets challenging. Ask GitLab Duo Chat for help.
  2. In your IDE, select the source code, and use the /refactor slash command in the Chat prompt. You can refine the prompt to focus on specific design patterns (functions, object-oriented classes, etc.), /refactor into testable functions for example._

    • After ensuring more readable code, tests need to be written. What are potential extreme cases, or random data examples for unit tests? Research and implementation in various frameworks can take time.
  3. In your IDE, select the source code, and use the /tests slash command in the Chat prompt. You can also refine the prompt to focus in specific test frameworks, scenarios, input methods, etc.

    • Code quality and test coverage reports are green again. Focus on efficient DevSecOps workflows with Code Suggestions again.

More scenarios are described in the GitLab Duo use cases documentation.

Use Chat to generate build configuration

The time-intensive research on getting started with a new project can be exhausting. Especially with different paths to do it right, or alternative frameworks, this can lead to more work than anticipated. Newer programming languages like Rust propose one way (Cargo), while Java, C++, etc. offer multiple ways and additional configuration languages on top (Kotlin DSL, CMake DSL, etc.).

Take advantage of asking GitLab Duo how to start a project, generate specific configuration examples for build tools (e.g. Please show a gradle.build example for Spring Boot), and reduce the time to start developing, building, and testing source code.

  1. Java, Gradle, Spring Boot: Please show a gradle.build example for Spring Boot
  2. C++, CMake, clang: Please show a basic CMake configuration file for C++17, using clang as compiler.
  3. Python: Please show how to initialize and configure a Python project on the CLI
  4. Rust: Please show how to initialize and configure a Rust project., followed by a refinement question: Explain the structure of Cargo.toml.
  5. Go: Please show how to initialize and configure a Go project.

Use Chat to explain potential vulnerabilities

Let us assume that some PHP code was generated to create a web form. The code might be vulnerable to security issues.

<?php // Create a feedback form for user name, email, and comments // Render a HTML form $name = $_POST['name']; $email = $_POST['email']; $comments = $_POST['comments']; echo '<form method="post">'; echo '<label for="name">Name:</label>'; echo '<input type="text" id="name" name="name">'; echo '<label for="email">Email:</label>'; echo '<input type="email" id="email" name="email">'; echo '<label for="comments">Comments:</label>'; echo '<textarea id="comments" name="comments"></textarea>'; echo '<input type="submit" value="Submit">'; echo '</form>'; ?>

Select the source code, and ask Chat to explain, using a refined prompt with /explain why this code is vulnerable to bad security actors.

Code Suggestions - Chat explains potential vulnerability

Tip: We are investigating and learning in the local developer environment. The vulnerable source code can be fixed before it reaches a Git push and merge request that trigger security scanning, which will unveil and track the problems, too. Learning about security vulnerabilities helps improve the developer experience.

Combine vulnerability resolution with Code Suggestions

Lets look into another example with an intentional vulnerability resolution challenge, and see if we can use Code Suggestions in combination with vulnerability resolution. The linked project has been preconfigured with static application security testing (SAST) scanning. You can follow these steps to configure GitLab SAST by using the SAST CI/CD component in the .gitlab-ci.yml CI/CD configuration file.

include: # Security: SAST (for vulnerability resolution) - component: gitlab.com/components/sast/[email protected]

After inspecting the vulnerability dashboard and details, you can use vulnerability explanation to better understand the context and potential problems. Vulnerability resolution creates a rerge request with a proposed source code fix for a detected security vulnerability.

Sometimes, it can be necessary to refine the suggested code. Navigate into the created MR, and either copy the Git branch path for local Git fetch, or open the Web IDE from the Edit button to continue in the browser. Navigate into the source code sections with the fixed code portions, and modify the code with a comment:

// refactor using safe buffers, null byte termination

duo code suggestions - with vulnerability resolution proposal

Alternatively, you can also open Chat, select the source code and use the /refactor slash command.

duo code suggestions - with vulnerability resolution add duo chat refactor

A full example is available in the GitLab Duo use cases documentation.

Here is a recording of that example:

<!-- blank line --> <figure class="video_container"> <iframe src="https://www.youtube.com/embed/Ypwx4lFnHP0" frameborder="0" allowfullscreen="true"> </iframe> </figure> <!-- blank line -->

More tips

Verify code quality and security

More generated code requires quality assurance, testing, and security measures. Benefit from all features on a DevSecOps platform:

  1. CI/CD components and pipeline efficiency
  2. Code quality
  3. Code test coverage
  4. Application security
  5. Observability

Learn as a team, and understand AI impact

Adapt and explore with dedicated team collaboration sessions, and record them for other teams to benefit from later. You can also follow the GitLab Duo Coffee Chat playlist on YouTube.

Read about AI impact metrics, including How to put generative AI to work in your DevSecOps environment and the Developing GitLab Duo: AI Impact analytics dashboard measures the ROI of AI. Visit the AI Transparency Center to learn more about data usage, transparency, and AI ethics at GitLab.

Development is a marathon, not a sprint

Sometimes, code suggestions might take longer to load, compared to local auto-completion features. Take this time as an advantage, and think about the current algorithm or problem you are trying to solve. Often, a secondary thought can lead to more refined ideas. Or you can take a short break to take a sip from your preferred drink, and continue refreshed when the suggestions arrive.

Some algorithms are super complex, or require code dependencies which cannot be resolved through auto-completion help. Proprietary and confidential code may provide less context to the large language models, and, therefore, require more context in the comments for Code Suggestions. Follow your own pace and strategy, and leverage Code Suggestions in situations where they help with boilerplate code, or helper functions.

Tip: Explore Repository X-Ray for more Code Suggestions context, and test experimental features, for example, support for more languages in VS Code. More insights can be found in the epic to improve acceptance rate for Code Suggestions.

Contribute using GitLab Duo

You can use GitLab Duo to contribute to open source projects, using Code Suggestions, code refactoring, documentation through explanations, or test generation.

GitLab customers can co-create GitLab using GitLab Duo, too. Follow the updated guidelines for AI-generated contributions, and watch an example recording from the GitLab Duo Coffee Chat: Contribute to GitLab using Code Suggestions and Chat:

<!-- blank line --> <figure class="video_container"> <iframe src="https://www.youtube.com/embed/TauP7soXj-E" frameborder="0" allowfullscreen="true"> </iframe> </figure> <!-- blank line -->

Share your feedback

GitLab Duo Code Suggestions enables more efficient development workflows. It requires hands-on practice and exercise through tutorials, team workshops, and guided training. Automated workflows with code quality, security scanning, and observability help tackle challenges with newly introduced source code at a much higher frequency. Taking advantage of all GitLab Duo features, including Chat, greatly improves the developer experience on the most comprehensive AI-powered DevSecOps platform.

Use the best practices in this tutorial to kickstart your journey, follow the GitLab Duo documentation, and ask our teams for GitLab Duo AI workshops (I have already shadowed customer workshops, they are great!). Please share your Code Suggestions feedback in this issue, including screenshots and videos (when possible).

Try GitLab Duo for free today!

Read Entire Article