Skip to content

GitHub Copilot Custom Instructions: Write Less, Get Better Results

GitHub Copilot custom instructions give developers a powerful way to enhance their coding experience. By setting up custom instructions, you can significantly improve the quality of the code suggestions while writing shorter prompts. Moreover, GitHub Copilot for VS Code becomes more aligned with your coding style and project requirements through these personalized instructions.

Why GitHub Copilot Custom Instructions Matter

When you’re working on a project, you often need to provide detailed prompts to get the code you want from GitHub Copilot. However, with custom instructions, you can reduce the time spent crafting perfect prompts. Furthermore, these instructions serve as persistent context for all your interactions with Copilot.

The main benefits include:

  • Shorter prompts with better results
  • Consistent coding style across your team
  • Time savings through personalized responses
  • Better alignment with project requirements

Let’s dive into how you can set up and leverage these custom instructions in your workflow.

Setting Up GitHub Copilot Custom Instructions in VS Code

Setting up custom instructions for GitHub Copilot is straightforward. Additionally, you can apply these instructions at different levels depending on your needs.

Creating a Basic Custom Instructions File

To get started, you need to create a specific file structure:

  1. First, create a directory named .github at the root of your project
  2. Then, inside that directory, create a markdown file named copilot-instructions.md
Project Root
├── .github
│   └── copilot-instructions.md
└── ...

The copilot-instructions.md file is a simple markdown document that contains your custom instructions. In addition, you can structure this file however you want, but it’s best to keep it clear and organized.

Here’s a basic example:

# Coding Style Guide

## JavaScript Guidelines
- Use 2 spaces for indentation
- Prefer single quotes for strings
- Use camelCase for variable names
- Avoid spaces inside parentheses

## Database Naming Conventions
- Table names should be plural
- Column names should be snake_case
- Primary keys should be named 'id'

Once you’ve created this file, GitHub Copilot will automatically include these instructions as context when generating code suggestions. As a result, you’ll get more relevant and consistent code that matches your preferences.

Workspace-Level Custom Instructions

For team projects, you might want to set workspace-level custom instructions. To do this:

  1. Open your VS Code settings (File > Preferences > Settings)
  2. Search for “Copilot”
  3. Look for settings related to file references

You can add multiple reference files to provide context for different aspects of your project:

{
  "github.copilot.advanced": {
    "fileReferenceScheme": "workspace",
    "fileReferences": {
      "codeGeneration": [
        ".github/code-style.md",
        "docs/architectural-guidelines.md"
      ],
      "commitMessage": [
        ".github/commit-style.md"
      ],
      "codeReview": [
        ".github/review-checklist.md"
      ],
      "testGeneration": [
        ".github/test-guidelines.md"
      ]
    }
  }
}

This approach allows you to maintain separate instruction files for different Copilot features. Consequently, you can tailor the instructions specifically for code generation, commit messages, code reviews, or test generation.

Creating Effective Custom Instructions

To maximize the benefits of GitHub Copilot custom instructions, you should focus on providing clear guidance. Furthermore, your instructions should cover the most important aspects of your coding style and project requirements.

Coding Style Specifications

Include detailed information about your coding style preferences:

## Coding Style

### JavaScript
- Use 2-space indentation
- Always use semicolons
- Variable naming: camelCase for variables and functions, PascalCase for classes
- Prefer const over let, avoid var
- Use template literals for string interpolation
- Prefer arrow functions for callbacks

### SQL
- Keywords should be UPPERCASE
- Table names should be plural
- Use snake_case for column names
- Include comments for complex queries

Project-Specific Guidelines

Add context about your project structure and patterns:

## Project Architecture

- This project uses the Repository pattern
- Data access should always go through repository classes
- Business logic belongs in service classes
- Controllers should be thin and only handle request/response
- Use dependency injection for all services

Testing Requirements

Specify your testing approach:

## Testing Guidelines

- Use AAA pattern (Arrange, Act, Assert)
- Test names should follow the pattern: `should_ExpectedBehavior_When_StateUnderTest`
- Mock external dependencies
- Each test should test only one thing
- Coverage requirements: 80% minimum

Leveraging Custom Instructions for Different Copilot Features

GitHub Copilot offers several features beyond just code suggestions. Additionally, you can customize instructions for each of these features.

Custom Instructions for Code Generation

When asking Copilot to generate code, your custom instructions will guide its output. For instance, if you’re learning about tail recursion and ask Copilot about it:

Tell me about tail recursion

Without custom instructions, Copilot might provide a good explanation but with code that doesn’t match your style. However, with custom instructions, the code examples will follow your team’s conventions automatically.

Custom Instructions for Commit Messages

GitHub Copilot can generate commit messages for you when you’re ready to commit your changes. To customize this:

  1. Open your source control panel in VS Code
  2. Hover over the sparkle icon
  3. Copilot will suggest a commit message based on your changes

You can customize the format of these messages by adding specific instructions:

## Commit Message Format

- Start with a category (feat, fix, docs, style, refactor, test, chore)
- Use the format: `category: short description`
- Use imperative mood ("add" not "added")
- Keep the first line under 50 characters
- Add emoji at the beginning to categorize the change:
  - for new features
  - for bug fixes
  - for documentation
  - for style changes

After adding these instructions to your settings, your commit messages will follow this format, making your version history more consistent and readable.

Custom Instructions for Code Review

One of the most powerful features is using Copilot for pre-commit code reviews:

Review my code before I commit it

With custom review instructions, Copilot will check your code against your team’s standards:

## Code Review Checklist

- Check for security vulnerabilities
- Ensure error handling is comprehensive
- Verify consistent naming conventions
- Look for potential performance issues
- Confirm adherence to architectural patterns
- Check that code is properly documented

This saves significant time by catching issues before opening a pull request.

Advanced Custom Instruction Techniques

As you become more familiar with GitHub Copilot custom instructions, you can implement more advanced techniques. Moreover, these techniques can further enhance your productivity.

Incorporating Database Schemas

Including your database schema in your custom instructions helps Copilot understand your data structure:

CREATE TABLE users (
  id INTEGER PRIMARY KEY,
  username TEXT NOT NULL UNIQUE,
  email TEXT NOT NULL UNIQUE,
  password_hash TEXT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE posts (
  id INTEGER PRIMARY KEY,
  user_id INTEGER NOT NULL,
  title TEXT NOT NULL,
  content TEXT NOT NULL,
  published BOOLEAN DEFAULT FALSE,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id)
);

When added as a reference file, this schema allows Copilot to generate appropriate queries, models, and related code that correctly references your database structure.

Using Custom Instructions for Framework-Specific Code

If you’re using specific frameworks, include their conventions in your instructions:

## React Component Guidelines

- Use functional components with hooks
- Implement error boundaries for top-level components
- Props should use destructuring
- Use custom hooks for shared logic
- Follow the container/presentational pattern
- Use React.memo for performance optimization where appropriate

This helps Copilot generate framework-compliant code that follows best practices.

Multi-Language Project Instructions

For projects using multiple programming languages, organize your instructions by language:

# Multi-Language Guidelines

## JavaScript/TypeScript
- Use ES6+ features
- Type everything in TypeScript
- Prefer interfaces over types for objects

## Python
- Follow PEP 8
- Use type hints
- Use dataclasses for data containers

## Rust
- Follow the official Rust style guide
- Use the ? operator for error handling
- Prefer iterators over for loops

This ensures that regardless of what language file you’re working in, Copilot will follow the appropriate conventions.

Real-World Examples of GitHub Copilot Custom Instructions

Let’s look at some practical examples of how custom instructions can improve your workflow.

Example 1: Converting SQL Schema to Prisma Schema

If you have a SQL schema defined in your custom instructions:

CREATE TABLE users (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,
  email TEXT NOT NULL UNIQUE,
  role TEXT DEFAULT 'user'
);

CREATE TABLE posts (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  title TEXT NOT NULL,
  content TEXT,
  published BOOLEAN DEFAULT FALSE,
  author_id INTEGER NOT NULL,
  FOREIGN KEY (author_id) REFERENCES users(id)
);

You can ask Copilot:

Generate a Prisma schema for my database

Copilot will use your SQL schema as context and generate:

model User {
  id    Int     @id @default(autoincrement())
  name  String
  email String  @unique
  role  String  @default("user")
  posts Post[]
}

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false)
  author    User    @relation(fields: [authorId], references: [id])
  authorId  Int
}

This conversion would typically take significant manual effort, but with custom instructions, Copilot does it for you.

Example 2: Generating Unit Tests

With testing guidelines in your custom instructions:

## Testing Guidelines
- Use Jest for unit tests
- Follow AAA pattern (Arrange, Act, Assert)
- Mock external dependencies
- Test files should be named [filename].test.js

You can ask Copilot to generate tests for your code:

Write tests for my User class

Copilot will generate tests that follow your guidelines:

// User.test.js
import { User } from './User';
import { UserRepository } from './UserRepository';

jest.mock('./UserRepository');

describe('User', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  test('should_ReturnUserProfile_When_ProfileMethodCalled', () => {
    // Arrange
    const mockUser = new User(1, 'John Doe', 'john@example.com');
    
    // Act
    const profile = mockUser.getProfile();
    
    // Assert
    expect(profile).toEqual({
      id: 1,
      name: 'John Doe',
      email: 'john@example.com'
    });
  });

  test('should_SaveUserToRepository_When_SaveMethodCalled', async () => {
    // Arrange
    const mockUser = new User(1, 'John Doe', 'john@example.com');
    UserRepository.save.mockResolvedValue(true);
    
    // Act
    const result = await mockUser.save();
    
    // Assert
    expect(UserRepository.save).toHaveBeenCalledWith(mockUser);
    expect(result).toBe(true);
  });
});

Comparing Coding With and Without Custom Instructions

To really understand the impact of GitHub Copilot custom instructions, let’s compare the experience with and without them.

Without Custom Instructions

When asking Copilot about tail recursion without custom instructions:

Explain tail recursion

You might get a response like:

function factorial(n, accumulator = 1) {
    if (n <= 1) {
        return accumulator;
    }
    
    return factorial(n - 1, n * accumulator);
}

// Usage
console.log(factorial(5));  // 120

This code works, but it may not match your coding style or conventions.

With Custom Instructions

With custom instructions specifying your JavaScript style:

## JavaScript Style
- Use arrow functions when possible
- Use 2-space indentation
- Use semicolons
- Prefer const over let
- Include JSDoc comments for functions

The same query produces:

/**
 * Calculates factorial using tail recursion
 * @param {number} n - The number to calculate factorial for
 * @param {number} accumulator - The accumulated value
 * @return {number} The factorial result
 */
const factorial = (n, accumulator = 1) => {
  if (n <= 1) {
    return accumulator;
  }
  
  return factorial(n - 1, n * accumulator);
};

// Usage
console.log(factorial(5));  // 120

Notice the use of arrow functions, consistent indentation, JSDoc comments, and other style elements specified in your instructions.

Best Practices for Team-Wide Custom Instructions

To maximize the benefits of GitHub Copilot custom instructions across your team, consider these best practices:

  1. Store instructions in version control: Keep your .github/copilot-instructions.md file in your repository so all team members benefit from it.
  2. Start with a template: Create a base template for new projects that includes your team’s standard conventions.
  3. Regularly update instructions: As your project evolves, update your custom instructions to reflect new patterns and requirements.
  4. Be specific but concise: Provide enough detail to guide Copilot effectively, but avoid overwhelming it with too many instructions.
  5. Use separate files for different concerns: Split your instructions into multiple files for different aspects of development (coding style, architecture, testing, etc.).
  6. Include examples: Where appropriate, include examples of what good code looks like in your project.
  7. Reference external documentation: Link to more detailed guides and documentation when necessary.
## API Endpoints

All API endpoints should follow REST conventions and be structured as follows:

- GET /resources - List all resources
- GET /resources/:id - Get a specific resource
- POST /resources - Create a new resource
- PUT /resources/:id - Update a resource
- DELETE /resources/:id - Delete a resource

For more details, see our [API Design Guidelines](https://company-docs.example.com/api-guidelines).

Optimizing Custom Instructions Over Time

As with any tool, your use of GitHub Copilot custom instructions should evolve over time. Furthermore, you can refine your instructions based on how well they work in practice.

Monitoring Effectiveness

Pay attention to how well Copilot’s suggestions match your expectations. If you find yourself frequently editing generated code in the same ways, update your instructions to address these patterns.

Gathering Team Feedback

Regularly ask your team about their experience with Copilot and the custom instructions. Collect feedback on:

  • Areas where Copilot consistently provides inappropriate suggestions
  • Common modifications needed to generated code
  • Features or patterns that aren’t well covered by current instructions

Iterative Refinement

Start with basic instructions and gradually refine them:

  1. Begin with core coding style and project structure
  2. Add specialized instructions for areas that need improvement
  3. Incorporate domain-specific knowledge and terminology
  4. Add examples for complex or unique patterns

Conclusion

GitHub Copilot custom instructions represent a powerful way to enhance your development workflow. By providing persistent context for your project, you can write shorter prompts while getting better, more tailored responses from Copilot.

The key benefits include:

  • Writing less while getting more relevant code suggestions
  • Ensuring consistent coding practices across your team
  • Saving time on repetitive coding tasks
  • Improving code quality through standardized approaches

To get started:

  1. Create a .github/copilot-instructions.md file
  2. Add your coding standards and project specifics
  3. Refine your instructions over time as your project evolves

By implementing custom instructions, you transform GitHub Copilot from a general-purpose code assistant into a specialized pair programmer that understands your project’s unique requirements and conventions.

Additional Resources

To learn more about GitHub Copilot and custom instructions, check out these resources:

By mastering GitHub Copilot custom instructions, you’ll transform your development experience and significantly boost your productivity.


Discover more from teguhteja.id

Subscribe to get the latest posts sent to your email.

1 thought on “GitHub Copilot Custom Instructions: Write Less, Get Better Results”

  1. Pingback: Amazing Odoo GitHub Actions CICD: 7 Steps

Leave a Reply

WP Twitter Auto Publish Powered By : XYZScripts.com