### Initial Usage Statistics Example Source: https://sourcegraph.com/docs/api/graphql/api-docs An example of initial usage statistics, including start time and various user counts. This data provides a snapshot of site activity. ```json { "startTime": "abc123", "userCount": 123, "registeredUserCount": 123, "anonymousUserCount": 987, "integrationUserCount": 123 } ``` -------------------------------- ### Monitor Startup Script Source: https://sourcegraph.com/docs/self-hosted/deploy/docker-compose/google-cloud.md Follows the logs of the startup script in real-time to monitor the progress of the Sourcegraph installation and setup process. ```bash tail -c +0 -f /var/log/syslog | grep startup-script ``` -------------------------------- ### Sourcegraph Docker Deployment Startup Script Source: https://sourcegraph.com/docs/self-hosted/deploy/docker-compose/google-cloud.md This bash script automates the setup of Sourcegraph on a Google Cloud VM. It clones the deployment repository, formats and mounts a persistent disk for Docker data, and installs Docker. Ensure you replace the placeholder for DEPLOY_SOURCEGRAPH_DOCKER_FORK_REVISION with your desired version. ```bash #!/usr/bin/env bash set -euxo pipefail ############################################################################### # ACTION REQUIRED: REPLACE THE URL AND REVISION WITH YOUR DEPLOYMENT REPO INFO ############################################################################### # Please read the notes below the script if you are cloning a private repository DEPLOY_SOURCEGRAPH_DOCKER_FORK_CLONE_URL='https://github.com/sourcegraph/deploy-sourcegraph-docker.git' DEPLOY_SOURCEGRAPH_DOCKER_FORK_REVISION={CURRENT_VERSION} ##################### NO CHANGES REQUIRED BELOW THIS LINE ##################### # IMPORTANT: DO NOT MAKE ANY CHANGES FROM THIS POINT ONWARD DEPLOY_SOURCEGRAPH_DOCKER_CHECKOUT='/root/deploy-sourcegraph-docker' DOCKER_COMPOSE_VERSION='1.29.2' DOCKER_DAEMON_CONFIG_FILE='/etc/docker/daemon.json' DOCKER_DATA_ROOT='/mnt/docker-data' PERSISTENT_DISK_DEVICE_NAME='/dev/sdb' PERSISTENT_DISK_LABEL='sourcegraph' # Install git sudo apt-get update -y sudo apt-get install -y git # Clone the deployment repository git clone "${DEPLOY_SOURCEGRAPH_DOCKER_FORK_CLONE_URL}" "${DEPLOY_SOURCEGRAPH_DOCKER_CHECKOUT}" cd "${DEPLOY_SOURCEGRAPH_DOCKER_CHECKOUT}" git checkout "${DEPLOY_SOURCEGRAPH_DOCKER_FORK_REVISION}" # Format (if unformatted) and then mount the attached volume device_fs=$(sudo lsblk "${PERSISTENT_DISK_DEVICE_NAME}" --noheadings --output fsType) if [ "${device_fs}" == "" ] ## only format the volume if it isn't already formatted then sudo mkfs.ext4 -m 0 -E lazy_itable_init=0,lazy_journal_init=0,discard "${PERSISTENT_DISK_DEVICE_NAME}" fi sudo e2label "${PERSISTENT_DISK_DEVICE_NAME}" "${PERSISTENT_DISK_LABEL}" sudo mkdir -p "${DOCKER_DATA_ROOT}" sudo mount -o discard,defaults "${PERSISTENT_DISK_DEVICE_NAME}" "${DOCKER_DATA_ROOT}" # Mount file system by label on reboot sudo echo "LABEL=${PERSISTENT_DISK_LABEL} ${DOCKER_DATA_ROOT} ext4 discard,defaults,nofail 0 2" | sudo tee -a /etc/fstab sudo umount "${DOCKER_DATA_ROOT}" sudo mount -a # Install, configure, and enable Docker curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo apt-get update -y sudo apt-get install -y software-properties-common sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" sudo apt-get update -y apt-cache policy docker-ce apt-get install -y docker-ce docker-ce-cli containerd.io ## Enable Docker at startup sudo systemctl enable --now docker ## Install jq for scripting sudo apt-get update -y sudo apt-get install -y jq ``` -------------------------------- ### Sourcegraph Docker Deployment Startup Script Source: https://sourcegraph.com/docs/self-hosted/deploy/docker-compose/digitalocean.md This bash script automates the setup of a Sourcegraph instance on a DigitalOcean Droplet. It clones the deployment repository, formats and mounts persistent storage, installs Docker, and configures it to use the mounted volume. Ensure you replace `{CURRENT_VERSION}` with your desired Sourcegraph version. ```bash #!/usr/bin/env bash set -euxo pipefail ############################################################################### # ACTION REQUIRED: REPLACE THE URL AND REVISION WITH YOUR DEPLOYMENT REPO INFO ############################################################################### # Please read the notes below the script if you are cloning a private repository DEPLOY_SOURCEGRAPH_DOCKER_FORK_CLONE_URL='https://github.com/sourcegraph/deploy-sourcegraph-docker.git' DEPLOY_SOURCEGRAPH_DOCKER_FORK_REVISION={CURRENT_VERSION} ##################### NO CHANGES REQUIRED BELOW THIS LINE ##################### DEPLOY_SOURCEGRAPH_DOCKER_CHECKOUT='/root/deploy-sourcegraph-docker' DOCKER_DATA_ROOT='/mnt/docker-data' DOCKER_COMPOSE_VERSION='1.29.2' DOCKER_DAEMON_CONFIG_FILE='/etc/docker/daemon.json' PERSISTENT_DISK_DEVICE_NAME='/dev/sda' # Install git sudo apt-get update -y sudo apt-get install -y git # Clone the deployment repository git clone "${DEPLOY_SOURCEGRAPH_DOCKER_FORK_CLONE_URL}" "${DEPLOY_SOURCEGRAPH_DOCKER_CHECKOUT}" cd "${DEPLOY_SOURCEGRAPH_DOCKER_CHECKOUT}" git checkout "${DEPLOY_SOURCEGRAPH_DOCKER_FORK_REVISION}" # Format (if unformatted) and then mount the attached volume device_fs=$(sudo lsblk "${PERSISTENT_DISK_DEVICE_NAME}" --noheadings --output fsType) if [ "${device_fs}" == "" ] then sudo mkfs.ext4 -m 0 -E lazy_itable_init=0,lazy_journal_init=0,discard "${PERSISTENT_DISK_DEVICE_NAME}" fi sudo mkdir -p "${DOCKER_DATA_ROOT}" sudo mount -o discard,defaults "${PERSISTENT_DISK_DEVICE_NAME}" "${DOCKER_DATA_ROOT}" # Mount file system by UUID on reboot DISK_UUID=$(sudo blkid -s UUID -o value "${PERSISTENT_DISK_DEVICE_NAME}") sudo echo "UUID=${DISK_UUID} ${DOCKER_DATA_ROOT} ext4 discard,defaults,nofail 0 2" >> '/etc/fstab' sudo umount "${DOCKER_DATA_ROOT}" sudo mount -a # Install, configure, and enable Docker curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" sudo apt-get update -y apt-cache policy docker-ce apt-get install -y docker-ce docker-ce-cli containerd.io ## Enable Docker at startup sudo systemctl enable --now docker # Install jq for scripting sudo apt-get update -y sudo apt-get install -y jq ## Initialize the config file with empty json if it doesn't exist if [ ! -f "${DOCKER_DAEMON_CONFIG_FILE}" ] then mkdir -p $(dirname "${DOCKER_DAEMON_CONFIG_FILE}") echo '{}' > "${DOCKER_DAEMON_CONFIG_FILE}" fi ## Point Docker storage to mounted volume tmp_config=$(mktemp) trap "rm -f ${tmp_config}" EXIT sudo cat "${DOCKER_DAEMON_CONFIG_FILE}" | sudo jq --arg DATA_ROOT "${DOCKER_DATA_ROOT}" '.["data-root"]=$DATA_ROOT' > "${tmp_config}" sudo cat "${tmp_config}" > "${DOCKER_DAEMON_CONFIG_FILE}" ## Restart Docker daemon to pick up new changes sudo systemctl restart --now docker ``` -------------------------------- ### Start PostgreSQL in Single-Container Instance Source: https://sourcegraph.com/docs/self-hosted/how-to/run-psql.md After exec'ing into the container, run this command to start the PostgreSQL client and connect to the database. No password is required by default. ```bash psql -U postgres ``` -------------------------------- ### Good Example: Specific Email Validation Prompt with Test Cases Source: https://sourcegraph.com/docs/cody/prompts-guide.md Provide clear requirements, expected return values, and concrete examples of valid and invalid inputs to guide code generation. ```plaintext Create a function to validate email addresses in JavaScript. Return true for valid email addresses and false for invalid ones. Here are some example test cases: Valid: - "john@example.com" - "jane.doe@example.co.uk" Invalid: - "john@example" - "jane.doe@example." - "invalid.email" Please write the function ``` -------------------------------- ### Install All Required Executor Dependencies Source: https://sourcegraph.com/docs/self-hosted/executors/deploy-executors-binary.md Run the `executor install all` command as root to automatically set up and configure all necessary dependencies for running workloads in isolation. ```bash executor install all # OR run the following, to see how to install/configure components separately. executor install --help ``` -------------------------------- ### Check Docker Installation Source: https://sourcegraph.com/docs/batch-changes/troubleshooting.md Confirm that Docker is installed and configured correctly. This command tests Docker by running the `hello-world` image. ```bash docker run hello-world ``` -------------------------------- ### Initial Prompt for Order Price Calculation Source: https://sourcegraph.com/docs/cody/prompts-guide.md Start with a general prompt to get initial code, then refine it with specific requirements. ```plaintext I need to calculate the total price of an order. Help me write the function ``` -------------------------------- ### Install Go SCIP Indexer Source: https://sourcegraph.com/docs/code-navigation/how-to/index-a-go-repository.md Installs the scip-go command-line tool, which is used to generate SCIP index files for Go projects. Ensure Go is installed and configured in your PATH. ```shell go install github.com/sourcegraph/scip-go/cmd/scip-go@latest ``` -------------------------------- ### Enable and Start Docker Service Source: https://sourcegraph.com/docs/self-hosted/deploy/docker-compose/azure.md Enables the Docker service to start automatically on boot and starts it immediately. This command is essential for Docker to function. ```bash sudo systemctl enable --now docker ``` -------------------------------- ### Install Docker Compose Source: https://sourcegraph.com/docs/self-hosted/deploy/docker-compose/digitalocean.md Installs Docker Compose and its bash completion script. Ensure DOCKER_COMPOSE_VERSION is set before running. ```bash curl -L "https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose chmod +x /usr/local/bin/docker-compose curl -L "https://raw.githubusercontent.com/docker/compose/${DOCKER_COMPOSE_VERSION}/contrib/completion/bash/docker-compose" -o /etc/bash_completion.d/docker-compose ``` -------------------------------- ### Install Cody CLI with npm Source: https://sourcegraph.com/docs/cody/clients/install-cli.md Use this command to install the Cody CLI globally using npm. Ensure you have Node.js v20 or newer and npm installed. ```shell npm install -g @sourcegraph/cody ``` -------------------------------- ### Verify Cody CLI installation Source: https://sourcegraph.com/docs/cody/clients/install-cli.md Run this command after installation to confirm that the Cody CLI is installed correctly and accessible. ```shell cody help ``` -------------------------------- ### Start Postgres Instance Separately Source: https://sourcegraph.com/docs/self-hosted/deploy/docker-compose/migrate.md Start only the PostgreSQL instance using a specific Docker Compose file to prepare for database restoration. ```bash docker-compose -f db-only-migrate.docker-compose.yaml up -d ``` -------------------------------- ### Start All Sourcegraph Containers Source: https://sourcegraph.com/docs/self-hosted/deploy/docker-compose/migrate.md Start all Sourcegraph services using the main Docker Compose configuration file after the database migration is complete. ```bash docker-compose -f docker-compose.yaml up -d ``` -------------------------------- ### Install Sourcegraph CLI for Linux Source: https://sourcegraph.com/docs/batch-changes/quickstart.md Installs the Sourcegraph CLI (`src`) for Linux. Ensure you replace `` with your actual Sourcegraph instance URL. ```bash curl -L https:///.api/src-cli/src_linux_amd64 -o /usr/local/bin/src chmod +x /usr/local/bin/src ``` -------------------------------- ### Another matched example for fmt.Sprintf Source: https://sourcegraph.com/docs/code-search/types/structural.md Another example of a `fmt.Sprintf` call matching the pattern for a string literal first argument. ```go fmt.Sprintf("%s/campaigns/%s", externalURL, string(campaignID)) ``` -------------------------------- ### Start Sourcegraph with Docker Compose Source: https://sourcegraph.com/docs/self-hosted/deploy/docker-compose/digitalocean.md Starts the Sourcegraph instance using Docker Compose. Assumes you are in the "docker-compose" directory of the Sourcegraph deployment repository. ```bash cd "${DEPLOY_SOURCEGRAPH_DOCKER_CHECKOUT}"/docker-compose docker-compose up -d --remove-orphans ``` -------------------------------- ### Install jq Source: https://sourcegraph.com/docs/self-hosted/deploy/docker-compose/azure.md Installs the 'jq' command-line JSON processor, which is used for manipulating JSON data in scripts. ```bash sudo apt-get update -y sudo apt-get install -y jq ``` -------------------------------- ### Configure EC2 User Data for Sourcegraph Deployment Source: https://sourcegraph.com/docs/self-hosted/deploy/docker-single-container/aws.md This user data script automates the setup of Docker and the deployment of the Sourcegraph server container on an EC2 instance. It ensures necessary directories are created, Docker is installed and configured, and the Sourcegraph container is started with persistent volumes and restart policies. ```cloud-config #cloud-config repo_update: true repo_upgrade: all runcmd: # Create the directory structure for Sourcegraph data - mkdir -p /home/ec2-user/.sourcegraph/config - mkdir -p /home/ec2-user/.sourcegraph/data # Install, configure, and enable Docker - yum update -y - amazon-linux-extras install docker - systemctl enable --now --no-block docker - sed -i -e 's/1024/10240/g' /etc/sysconfig/docker - sed -i -e 's/4096/40960/g' /etc/sysconfig/docker - usermod -a -G docker ec2-user # Install and run Sourcegraph. Restart the container upon subsequent reboots - [ sh, -c, 'docker run -d --publish 80:7080 --publish 443:7080 --publish 127.0.0.1:3370:3370 --restart unless-stopped --volume /home/ec2-user/.sourcegraph/config:/etc/sourcegraph --volume /home/ec2-user/.sourcegraph/data:/var/opt/sourcegraph sourcegraph/server:{CURRENT_VERSION_NO_V}' ] ``` -------------------------------- ### Default Site Configuration Example Source: https://sourcegraph.com/docs/admin/config/site-config.md A default site configuration example, including external URL and authentication provider settings. Note that 'externalURL' is commented out and requires configuration. ```json { // The externally accessible URL for Sourcegraph (i.e., what you type into your browser) // This is required to be configured for Sourcegraph to work correctly. // "externalURL": "https://sourcegraph.example.com", // The authentication provider to use for identifying and signing in users. // Only one entry is supported. // // The builtin auth provider with signup disallowed (shown below) means that // after the initial site admin signs in, all other users must be invited. // // Other providers are documented at https://sourcegraph.com/docs/admin/auth. "auth.providers": [ { "type": "builtin", "allowSignup": false } ] } ``` -------------------------------- ### File Range Example Source: https://sourcegraph.com/docs/api/graphql/api-docs An example JSON object representing a range within a file, specifying start and end positions. ```json {"start": Position, "end": Position} ``` -------------------------------- ### Compare Kustomize Overlays (Example 1) Source: https://sourcegraph.com/docs/self-hosted/deploy/kubernetes/operations.md Compares diff between resources generated by the k3s overlay for size xs instance and the k3s overlay for size xl instance. ```bash $ diff \ <(kubectl kustomize examples/k3s/xs) \ <(kubectl kustomize examples/k3s/xl) |\n more ``` -------------------------------- ### API Endpoint Naming Convention Update Source: https://sourcegraph.com/docs/technical-changelog.md REST API endpoints have been renamed to consistently use plural names. For example, `GET /.api/reviews/diagnostics/ID` replaces `GET /.api/review/diagnostic`. Refer to the OpenAPI spec for updated paths. ```text Renamed REST API endpoints to consistently use plural names in `/.api/review**` and `/.api/tool`. For example, `GET /.api/reviews/diagnostics/ID` instead of `GET /.api/review/diagnostic`. See OpenAPI spec for updated paths. Backport 864c824e184a7dc84df694797c5603883d72ccf1 from #3028 ``` -------------------------------- ### Onboarding Prompt for New Team Members Source: https://sourcegraph.com/docs/cody/prompts-guide.md Use this prompt to provide new team members with essential information about a project, including setup instructions. ```text @repo tell me about this project and how to set it up. ``` -------------------------------- ### FileDiffHunkRange GraphQL Example Source: https://sourcegraph.com/docs/api/graphql/api-docs An example of a FileDiffHunkRange object, representing a range within a file diff. It specifies the start line and the number of lines the hunk applies to. ```graphql { "oldRange": FileDiffHunkRange, "oldNoNewlineAt": true, "newRange": FileDiffHunkRange, "section": "abc123", "body": "abc123", "highlight": HighlightedDiffHunkBody } ``` -------------------------------- ### Monitor Sourcegraph Startup Script Source: https://sourcegraph.com/docs/self-hosted/deploy/docker-compose/digitalocean.md Follows the output of the cloud-init startup script to monitor the installation process. ```bash tail -f /var/log/cloud-init-output.log ``` -------------------------------- ### Install Sourcegraph CLI with npm Source: https://sourcegraph.com/docs/cli/explanations/versioning.md Install the Sourcegraph CLI globally using npm. This is useful if you are already using Node.js and npm in your development environment. ```bash npm install -g @sourcegraph/src ``` -------------------------------- ### Get Sourcegraph CLI Version Source: https://sourcegraph.com/docs/code-navigation/troubleshooting.md Use this command to check the version of the Sourcegraph CLI installed on your system. This is useful for troubleshooting upload issues. ```bash $ src version Current version: 3.26.0 Recommended Version: 3.26.1 ``` -------------------------------- ### Compare Kustomize Overlays (Example 2) Source: https://sourcegraph.com/docs/self-hosted/deploy/kubernetes/operations.md Compares diff between the new base cluster and the old cluster manifests generated by Kustomize. ```bash $ diff \ <(kubectl kustomize examples/base) \ <(kubectl kustomize examples/old-cluster) |\n more ``` -------------------------------- ### SlowRequest Example (GraphQL) Source: https://sourcegraph.com/docs/api/graphql/api-docs An example structure for a slow GraphQL request log, detailing fields like index, start time, duration, user, name, source, repository, variables, errors, query, and filepath. ```json { "index": "xyz789", "start": "2007-12-03T10:15:30Z", "duration": 123.45, "user": User, "name": "abc123", "source": "abc123", "repository": Repository, "variables": "abc123", "errors": ["xyz789"], "query": "abc123", "filepath": "xyz789" } ``` -------------------------------- ### Mounting and Running a Binary Source: https://sourcegraph.com/docs/batch-changes/batch-spec-yaml-reference.md Shows how to mount a local binary into a container and execute it. The binary can be specified as an absolute or relative path. ```yaml # Mount a binary and run the binary steps: run: /tmp/some-binary # execute the binary located at the mountpoint container: alpine:latest mount: - path: ./some-binary # or absolute path /my/local/path/some-binary mountpoint: /tmp/some-binary ``` -------------------------------- ### Query Recent Migration Logs Source: https://sourcegraph.com/docs/self-hosted/how-to/dirty-database.md Use this SQL query to get an overview of the most recent migration attempts, partitioned by schema and version, ordered by start time. ```sql WITH ranked_migration_logs AS ( SELECT migration_logs.* ROW_NUMBER() OVER (PARTITION BY schema, version ORDER BY started_at DESC) AS row_number FROM migration_logs ) SELECT * FROM ranked_migration_logs WHERE row_number = 1 ORDER BY version ``` -------------------------------- ### Get Commit Ancestors Source: https://sourcegraph.com/docs/api/graphql/api-docs Retrieves the commit log history for a repository, starting from a specific commit. ```APIDOC ## GET /api/v1/repos/{repoName}/commit/{oid}/ancestors ### Description Retrieves the log of commits consisting of this commit and its ancestors, with options for pagination and filtering. ### Method GET ### Endpoint `/api/v1/repos/{repoName}/commit/{oid}/ancestors` ### Parameters #### Path Parameters - **oid** (`GitObjectID!`) - Required - The Git object ID (OID) of the starting commit. #### Query Parameters - **first** (`Int`) - Optional - Returns the first n commits from the list. - **query** (`String`) - Optional - Return commits that match the query. - **path** (`String`) - Optional - Return commits that affect the path. - **follow** (`Boolean`) - Optional - Follow history beyond renames (only works for a single file). - **after** (`String`) - Optional - Return commits more recent than the specified date. - **afterCursor** (`String`) - Optional - Skip the first N commits of the repo before returning the number of commits as set in the field "first". - **before** (`String`) - Optional - Return commits older than the specified date. ### Request Example ```json { "first": 10, "path": "README.md", "after": "2023-01-01T00:00:00Z" } ``` ### Response #### Success Response (200) - **ancestors** (`GitCommitConnection`) - A connection object containing a list of ancestor commits. #### Response Example ```json { "ancestors": { "nodes": [ { ... commit object ... }, { ... commit object ... } ], "pageInfo": { ... } } } ``` ``` -------------------------------- ### Install IPTables Rules Source: https://sourcegraph.com/docs/self-hosted/executors/deploy-executors-binary-offline.md Use the executor binary to install necessary IPTables rules. This is crucial for preventing Firecracker VMs from communicating on private IPv4 addresses. ```shell $ executor install iptables-rules ``` -------------------------------- ### Log in to Sourcegraph Instance Source: https://sourcegraph.com/docs/batch-changes/troubleshooting.md Use this command to ensure `src` is configured correctly with your Sourcegraph instance. Replace `sourcegraph.example.com` with your instance's URL. ```bash src login https://sourcegraph.example.com ``` -------------------------------- ### Verify Sourcegraph pods Source: https://sourcegraph.com/docs/self-hosted/deploy/kubernetes.md After installation, use this command to watch the status of your Sourcegraph pods. Ensure all pods restart and show as 'Running' to confirm the upgrade has started successfully. ```sh $ kubectl get pods --watch ``` -------------------------------- ### Rebuild indexes in Docker Compose Source: https://sourcegraph.com/docs/self-hosted/how-to/rebuild-corrupt-postgres-indexes.md These commands are for rebuilding indexes in a Docker Compose setup. Scale down other services to prevent new connections, then start only the database container and execute psql. ```shell export DB=pgsql # change for other databases docker-compose down # bring all containers down docker start $DB # bring only the db container back up docker exec -it $DB sh psql -U sg -d sg -h localhost -p 3333 ``` -------------------------------- ### Good Example: Specific Discount Calculation Prompt Source: https://sourcegraph.com/docs/cody/prompts-guide.md Include clear requirements, discount tiers, and the desired function signature when asking Cody to implement logic. ```plaintext I need to calculate discounts based on customer loyalty points. - If the customer has loyalty points above 500, apply a 10% discount. - If the customer has loyalty points between 200 and 500, apply a 5% discount. - If the customer has loyalty points below 200, no discount is applied. Create a function that takes the total amount and loyalty points as input and returns an object with the discount percentage and discount amount. ``` -------------------------------- ### Example Batch Spec with Templating Source: https://sourcegraph.com/docs/batch-changes/batch-spec-templating.md This example demonstrates using the `join` template helper function to construct arguments for `run` commands based on repository search results and modified files from previous steps. ```yaml on: - repositoriesMatchingQuery: lang:go fmt.Sprintf("%d", :[v]) patterntype:structural -file:vendor steps: - run: comby -in-place 'fmt.Sprintf("%d", :[v])' 'strconv.Itoa(:[v])' ${{ join repository.search_result_paths " " }} # ^ templating starts here container: comby/comby - run: goimports -w ${{ join previous_step.modified_files " " }} # ^ templating starts here container: unibeautify/goimports ``` -------------------------------- ### Delete User by Username Source: https://sourcegraph.com/docs/cli/references/users/delete.md This example shows how to delete a user by their username. It first retrieves the user's ID using `src users get` and then passes it to the delete command. ```bash src users delete -id=$(src users get -f='{{.ID}}' -username=alice) ``` -------------------------------- ### Search and Get Result Count with `src api` Source: https://sourcegraph.com/docs/cli/references/api.md Use `src api` to perform a search query and retrieve the result count. This example demonstrates how to pass a query with variables to search for 'Router'. ```bash $ echo 'query($query: String!) { search(query: $query) { results { resultCount } } }' | src api 'query=Router' ``` -------------------------------- ### Example Settings Object Source: https://sourcegraph.com/docs/api/graphql/api-docs An example of a settings object, demonstrating the structure and types of fields it contains. ```graphql { "id": 987, "subject": SettingsSubject, "author": User, "createdAt": "2007-12-03T10:15:30Z", "contents": JSONCString, "configuration": Configuration } ``` -------------------------------- ### Delete an organization by name using ID lookup Source: https://sourcegraph.com/docs/cli/references/orgs/delete.md This example demonstrates deleting an organization by its name. It first retrieves the organization's ID using `src orgs get` and then uses that ID to delete the organization. ```bash src orgs delete -id=$(src orgs get -f='{{.ID}}' -name=abc-org) ``` -------------------------------- ### Include and Exclude Repositories Source: https://sourcegraph.com/docs/cody/capabilities/ignore-context.md When both `include` and `exclude` rules are specified, Cody uses repositories that match `include` patterns but do not match `exclude` patterns. This example allows repositories starting with 'github.com/sourcegraph/' but excludes those containing 'cody' or named 'github.com/sourcegraph/cody-analytics'. ```json { "cody.contextFilters": { // All repositories starting with "github.com/sourcegraph/" are allowed "include": [{"repoNamePattern": "^github\.com\/sourcegraph\/.+"}], // except for "github.com/sourcegraph/cody-analytics" // and the ones containing "cody" in their name. "exclude": [ { "repoNamePattern": "^github\.com\/sourcegraph\/cody-analytics$" }, {"repoNamePattern": ".*cody.*"} ] } } ``` -------------------------------- ### Clone, Push, and Create Private Repository Source: https://sourcegraph.com/docs/self-hosted/deploy/repositories.md Clone the bare reference repository, push its contents to your private repository, and then clone your private repository locally. This process sets up your isolated deployment environment. ```bash git clone --bare https://github.com/sourcegraph/$SG_DEPLOY_REPO_NAME cd $DEPLOY_REPO.git git push --mirror https://github.com/SG_DEPLOY_GITHUB_USERNAME/$SG_PRIVATE_DEPLOY_REPO_NAME.git cd .. rm -rf $DEPLOY_REPO.git git clone https://github.com/SG_DEPLOY_GITHUB_USERNAME/$SG_PRIVATE_DEPLOY_REPO_NAME.git ``` -------------------------------- ### Install Specific Version for Sourcegraph Instance on Linux Source: https://sourcegraph.com/docs/cli/explanations/versioning.md Download the Sourcegraph CLI binary compatible with your specific Sourcegraph instance URL for Linux. Replace `sourcegraph.example.com` with your instance's domain. ```bash curl -L https://sourcegraph.example.com/.api/src-cli/src_linux_amd64 -o /usr/local/bin/src chmod +x /usr/local/bin/src ``` -------------------------------- ### Include Repositories by Multiple Patterns Source: https://sourcegraph.com/docs/cody/capabilities/ignore-context.md When only `include` rules are specified, Cody is restricted to repositories matching these patterns. This example allows repositories starting with 'github.com/sourcegraph/' or containing 'cody'. A single match in the `include` rules is sufficient for a repository to be included. ```json { "cody.contextFilters": { // Only repositories whose names either start with "github.com/sourcegraph/" // or contain "cody" are allowed. "include": [ {"repoNamePattern": "^github\.com\/sourcegraph\/.+"}, {"repoNamePattern": ".*cody.*"} ] } } ``` -------------------------------- ### Example JSON Structure for Hunk Source: https://sourcegraph.com/docs/api/graphql/api-docs This JSON object represents the structure of a hunk, detailing its start and end lines, byte positions, revision, author, message, commit, and filename. ```json { "startLine": 123, "endLine": 123, "startByte": 987, "endByte": 123, "rev": "abc123", "author": Signature, "message": "abc123", "commit": GitCommit, "filename": "abc123" } ``` -------------------------------- ### Neovim Configuration for src-lsp Source: https://sourcegraph.com/docs/cli/references/lsp.md Example configuration for Neovim to integrate with the 'src lsp' server. Ensure 'src-lsp' is enabled after configuration. ```lua vim.lsp.config['src-lsp'] = { cmd = { 'src', 'lsp' }, root_markers = { '.git' }, filetypes = { 'go', 'typescript', 'python' }, } vim.lsp.enable('src-lsp') ``` -------------------------------- ### Install Sourcegraph CLI for Specific Instance on Mac OS Source: https://sourcegraph.com/docs/cli/explanations/versioning.md Download the Sourcegraph CLI binary compatible with your specific Sourcegraph instance URL. Replace `sourcegraph.example.com` with your instance's domain. ```bash curl -L https://sourcegraph.example.com/.api/src-cli/src_darwin_amd64 -o /usr/local/bin/src chmod +x /usr/local/bin/src ``` -------------------------------- ### ChunkMatch Example (JSON) Source: https://sourcegraph.com/docs/api/graphql/api-docs Illustrates a JSON structure for a chunk match, containing contiguous lines of content and the ranges within that content that matched a search query. Includes start position for the content. ```json { "content": "xyz789", "contentStart": Position, "ranges": [Range] } ``` -------------------------------- ### Mounting a Script and Supporting Files Source: https://sourcegraph.com/docs/batch-changes/batch-spec-yaml-reference.md Demonstrates mounting both a Python script and a directory of supporting files into a container, then executing the script. ```yaml # Mount a Python script and a directory with supporting files for the script and run the script steps: run: python /tmp/some-script.py container: python:latest mount: - path: ./some-script.py # or absolute path /my/local/path/some-script.py mountpoint: /tmp/some-script.py - path: ./supporting-files # or absolute path /my/local/path/supporting-files mountpoint: /tmp/supporting-files ``` -------------------------------- ### Hello World Batch Spec Example Source: https://sourcegraph.com/docs/batch-changes/troubleshooting.md This is a basic batch spec to add 'Hello World' to README files. It's useful for testing if batch changes work generally. ```yaml name: hello-world description: Add Hello World to READMEs # Find one repository with a README on: - repositoriesMatchingQuery: repohasfile:README count:1 # In each repository, run this command. Each repository's resulting diff is captured. steps: - run: IFS=$'\n'; echo Hello World | tee -a $(find -name README) container: alpine:3 # Describe the changeset (e.g., GitHub pull request) you want for each repository. changesetTemplate: title: Hello World body: My first batch change! branch: hello-world # Push the commit to this branch. commit: message: Append Hello World to all README files published: false ``` -------------------------------- ### Validate Executor Installation Source: https://sourcegraph.com/docs/self-hosted/executors/deploy-executors-binary-offline.md Run this command after installing the executor binary and meeting all dependencies to validate the installation. ```shell $ executor validate ``` -------------------------------- ### Apply Sourcegraph Kustomize Overlay Source: https://sourcegraph.com/docs/self-hosted/deploy/kubernetes/kustomize/eks.md Deploys the main Sourcegraph application using the AWS EKS quick-start Kustomize overlay. Ensure all prerequisites are met before running. ```bash kubectl apply --prune -l deploy=sourcegraph -k https://github.com/sourcegraph/deploy-sourcegraph-k8s/examples/aws ``` -------------------------------- ### Create Kustomization from Remote Resources Source: https://sourcegraph.com/docs/self-hosted/deploy/kubernetes/kustomize/gke.md Initialize a local Kustomize project by pulling remote resources from a specified URL. This is useful for starting with a standard configuration. ```bash kustomize create --resources https://github.com/sourcegraph/deploy-sourcegraph-k8s/examples/gke ``` -------------------------------- ### Get User Settings by Username with src config get Source: https://sourcegraph.com/docs/cli/references/config/get.md Retrieves configuration settings for a specific user by their username. This requires first getting the user's ID using 'src users get'. ```bash src config get -subject=$(src users get -f '{{.ID}}' -username=alice) ``` -------------------------------- ### Start Docker Compose Deployments Source: https://sourcegraph.com/docs/self-hosted/how-to/upgrade-postgres-12-16-builtin-dbs.md Bring up the specified PostgreSQL-related services after updating their images in `docker-compose.yaml`. ```bash docker-compose up -d pgsql codeintel-db codeinsights-db ``` -------------------------------- ### GET /deepsearch/v1/{conversation_id} - Get Conversation Source: https://sourcegraph.com/docs/deep-search/api.md Retrieves a specific conversation by its ID. Poll this endpoint to get the completed answer after creation. ```APIDOC ## GET /.api/deepsearch/v1/{conversation_id} ### Description Retrieves a specific conversation by its ID. Poll this endpoint to get the completed answer after creation. ### Method GET ### Endpoint `https://your-sourcegraph-instance.com/.api/deepsearch/v1/{conversation_id}` ### Parameters #### Path Parameters - **conversation_id** (integer) - Required - The ID of the conversation to retrieve. ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the conversation. - **questions** (array) - A list of questions within the conversation. - **id** (integer) - The unique identifier for the question. - **conversation_id** (integer) - The ID of the conversation this question belongs to. - **question** (string) - The text of the question. - **created_at** (string) - Timestamp when the question was created. - **updated_at** (string) - Timestamp when the question was last updated. - **status** (string) - The current status of the question (e.g., 'processing', 'completed'). - **title** (string) - The title of the answer. - **answer** (string) - The completed answer to the question. - **sources** (array) - Sources used to generate the answer. - **stats** (object) - Statistics related to the question processing. - **suggested_followups** (array) - Suggested follow-up questions. - **created_at** (string) - Timestamp when the conversation was created. - **updated_at** (string) - Timestamp when the conversation was last updated. - **user_id** (integer) - The ID of the user who created the conversation. - **read_token** (string) - A token for reading the conversation. - **viewer** (object) - Information about the viewer. - **quota_usage** (object) - Information about quota usage. - **share_url** (string) - A URL to share the conversation. #### Response Example ```json { "id": 140, "questions": [ { "id": 163, "conversation_id": 140, "question": "Does github.com/sourcegraph/sourcegraph have a README?", "created_at": "2025-09-24T08:14:06Z", "updated_at": "2025-09-24T08:14:15Z", "status": "completed", "title": "GitHub README check", "answer": "Yes, [github.com/sourcegraph/sourcegraph](https://sourcegraph.test:3443/github.com/sourcegraph/sourcegraph) has a [README.md](https://sourcegraph.test:3443/github.com/sourcegraph/sourcegraph/-/blob/README.md) file in the root directory.", "sources": [ { "type": "Repository", "link": "/github.com/sourcegraph/sourcegraph", "label": "github.com/sourcegraph/sourcegraph" } ], "stats": { "time_millis": 6369, "tool_calls": 1, "total_input_tokens": 13632, "cached_tokens": 12359, "cache_creation_input_tokens": 13625, "prompt_tokens": 11, "completion_tokens": 156, "total_tokens": 13694, "credits": 2 }, "suggested_followups": [ "What information does the README.md file contain?", "Are there other important documentation files in the repository?" ] } ], "created_at": "2025-09-24T08:14:06Z", "updated_at": "2025-09-24T08:14:15Z", "user_id": 1, "read_token": "caebeb05-7755-4f89-834f-e3ee4a6acb25", "viewer": {"is_owner": true}, "quota_usage": { "total_quota": 0, "quota_limit": -1, "reset_time": "2025-10-01T00:00:00Z" }, "share_url": "https://sourcegraph.test:3443/deepsearch/caebeb05-7755-4f89-834f-e3ee4a6acb25" } ``` ``` -------------------------------- ### Notice Configuration Example Source: https://sourcegraph.com/docs/admin/config/settings.md Example of how to configure site-wide notices with message, location, dismissibility, variant, and style overrides. This allows for customizable banners on the Sourcegraph instance. ```json "notices": [ { "message": "Your important message here! [Include a link for more information](http://example.com).", "location": "top", "dismissible": true, "variant": "danger", "styleOverrides": { "styleOverrides": { "backgroundColor": "#7f1d1d", "textColor": "#fecaca", "textCentered": true } } } ] ``` -------------------------------- ### Install Cody CLI with pnpm Source: https://sourcegraph.com/docs/cody/clients/install-cli.md Use this command to install the Cody CLI globally using pnpm. Ensure you have Node.js v20 or newer and pnpm installed. ```shell pnpm install -g @sourcegraph/cody ``` -------------------------------- ### Example UpgradeReadiness Information Source: https://sourcegraph.com/docs/api/graphql/api-docs This snippet shows example information regarding instance upgrade readiness, including schema drift details and a list of required out-of-band migrations. ```json { "schemaDrift": "xyz789", "requiredOutOfBandMigrations": [OutOfBandMigration] } ``` -------------------------------- ### Install Cody CLI with yarn Source: https://sourcegraph.com/docs/cody/clients/install-cli.md Use this command to install the Cody CLI globally using yarn. Ensure you have Node.js v20 or newer and yarn installed. ```shell yarn global add @sourcegraph/cody ``` -------------------------------- ### Compare Overlay with Running Cluster (Example) Source: https://sourcegraph.com/docs/self-hosted/deploy/kubernetes/operations.md Compares the diff between the k3s overlay for size xl instance and the instance that is connected with `kubectl`. ```bash $ kubectl kustomize examples/k3s/xl | kubectl diff -f - ``` -------------------------------- ### Aggregate Command Setup Operations (5m) Source: https://sourcegraph.com/docs/self-hosted/observability/dashboards.md Aggregate the total number of command setup operations over a 5-minute interval. Filters for Sourcegraph executor jobs with 'setup' operations. ```PromQL sum(increase(src_apiworker_command_total{op=~"setup.*",sg_job=~"^sourcegraph-executors.*"}[5m])) ``` -------------------------------- ### Download frontend binary using kubectl Source: https://sourcegraph.com/docs/self-hosted/pprof.md Copy the frontend binary from a Kubernetes pod to your local machine using `kubectl cp`. This binary is required to use downloaded profile data with `go tool pprof`. ```bash kubectl cp sourcegraph-frontend-xxxx:/usr/local/bin/frontend frontend-bin ``` -------------------------------- ### Install scip-typescript Source: https://sourcegraph.com/docs/code-navigation/how-to/index-a-typescript-and-javascript-repository.md Install the scip-typescript package globally using npm. ```sh npm install -g @sourcegraph/scip-typescript ``` -------------------------------- ### Install Docker and Sourcegraph on Google Cloud VM Source: https://sourcegraph.com/docs/self-hosted/deploy/docker-single-container/google-cloud.md This script installs Docker and then runs the Sourcegraph server container. Ensure you replace {CURRENT_VERSION_NO_V} with the desired version. It mounts configuration and data directories to persistent locations. ```bash #!/usr/bin/env bash curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" sudo apt-get update apt-cache policy docker-ce sudo apt-get install -y docker-ce mkdir -p /root/.sourcegraph/config mkdir -p /root/.sourcegraph/data docker run -d --publish 80:7080 --publish 443:7443 --restart unless-stopped --volume /root/.sourcegraph/config:/etc/sourcegraph --volume /root/.sourcegraph/data:/var/opt/sourcegraph sourcegraph/server:{CURRENT_VERSION_NO_V} ``` -------------------------------- ### Install Sourcegraph via Shell Script Source: https://sourcegraph.com/docs/self-hosted/deploy/single-node/script.md Execute this command to download and run the Sourcegraph installation script. Replace `` with required and optional parameters like the data disk device. ```sh curl -sfL https://raw.githubusercontent.com/sourcegraph/deploy/main/install/scripts/k3s/install.sh | bash -s -- ``` -------------------------------- ### Run Default Installation Validation Source: https://sourcegraph.com/docs/self-hosted/validation.md Execute `src validate install` without arguments to run the default validation checks for your Sourcegraph installation. Requires `SRC_ENDPOINT` and `SRC_ACCESS_TOKEN` environment variables. ```shell src validate install ``` -------------------------------- ### Install Sourcegraph CLI on Mac OS with Homebrew Source: https://sourcegraph.com/docs/cli/explanations/versioning.md Install the Sourcegraph CLI using Homebrew for easy management. This command installs the latest version available via the Homebrew tap. ```bash brew install sourcegraph/src-cli/src-cli ``` -------------------------------- ### Download CA Files to Local Machine Source: https://sourcegraph.com/docs/self-hosted/ssl-https-self-signed-cert-nginx.md Copies the root CA files from the Sourcegraph host to your local machine's mkcert directory. Replace `user` and `example.com` with your actual username and hostname. ```bash scp user@example.com:~/.sourcegraph/config/root* "$(mkcert -CAROOT)" ``` -------------------------------- ### Example Code Host Configuration Source: https://sourcegraph.com/docs/self-hosted/advanced-config-file.md This JSONC structure defines configurations for multiple code hosts, including GitHub and generic Git hosts. It demonstrates how to specify repositories and authentication details. ```jsonc { "GITHUB": [ { // First GitHub code host configuration: literally the JSON object from the code host config editor. "authorization": {}, "url": "https://github.com", "token": "...", "repositoryQuery": ["affiliated"] }, { // Another GitHub code host configuration. ... }, ], "OTHER": [ { // First "Generic Git host" code host configuration. "url": "https://mycodehost.example.com/repos", "repos": ["foo"], } ], "PHABRICATOR": [ { // Phabricator code host configuration. ... }, ] } ``` -------------------------------- ### Verify src-cli Installation Source: https://sourcegraph.com/docs/self-hosted/executors/deploy-executors-binary-offline.md Confirm that the src-cli tool is installed and check its version. ```shell $ src version ``` -------------------------------- ### Validate Installation with Specification File Source: https://sourcegraph.com/docs/self-hosted/validation.md Use `src validate install` with a YAML or JSON specification file to validate your Sourcegraph installation. Ensure the `SRC_ENDPOINT` and `SRC_ACCESS_TOKEN` environment variables are set for authentication. ```shell src validate install validate.yaml ``` ```shell src validate install validate.json ``` -------------------------------- ### Get Organization Settings by Name with src config get Source: https://sourcegraph.com/docs/cli/references/config/get.md Fetches configuration settings for a specific organization by its name. This involves using 'src orgs get' to obtain the organization's ID. ```bash src config get -subject=$(src orgs get -f '{{.ID}}' -name=abc-org) ``` -------------------------------- ### List settings for the current user Source: https://sourcegraph.com/docs/cli/references/config/list.md Use this command to list configuration settings for the currently authenticated user. Ensure your 'src' CLI has a valid access token configured. ```bash $ src config list ``` -------------------------------- ### Command Setup 99th Percentile Duration (5m) Source: https://sourcegraph.com/docs/self-hosted/observability/dashboards.md Measure the 99th percentile duration of successful command setup operations over 5 minutes. This helps identify latency outliers in job setup. ```PromQL sum by (le)(rate(src_apiworker_command_duration_seconds_bucket{op=~"setup.*",sg_job=~"^sourcegraph-executors.*"}[5m])) ``` -------------------------------- ### SiteUserOrderBy Enum Example Source: https://sourcegraph.com/docs/api/graphql/api-docs An example of the SiteUserOrderBy enum, which enumerates the ways a list of users can be ordered. This example shows ordering by username. ```json "USERNAME" ``` -------------------------------- ### Rendered Run Command Example 1 Source: https://sourcegraph.com/docs/batch-changes/batch-spec-templating.md This shows the final `run` command after `repository.search_result_paths` is replaced with actual file paths, demonstrating how templating dynamically targets specific files for the `comby` tool. ```yaml run: comby -in-place 'fmt.Sprintf("%d", :[v])' 'strconv.Itoa(:[v])' cmd/src/main.go internal/fmt/fmt.go ``` -------------------------------- ### Install Yarn Dependencies in Subdirectory Source: https://sourcegraph.com/docs/code-navigation/auto-indexing-configuration.md This configuration installs Yarn dependencies in a specific subdirectory (`lib/proj`) using a Node.js Docker image. It also sets `ignore-engines` to true to bypass engine checks during installation. ```json { "indexer": "node:alpine3.12@sha256:4435145...fd06fd3", "commands": ["yarn config set ignore-engines true", "yarn install"], "root": "lib/proj" } ``` -------------------------------- ### SiteUsersNumberRangeInput Example Source: https://sourcegraph.com/docs/api/graphql/api-docs An example of SiteUsersNumberRangeInput, used to filter users based on a numerical range. This example demonstrates filtering by greater than or equal to and less than or equal to values. ```json { "gte": 123.45, "lte": 123.45 } ``` -------------------------------- ### Use Compressed File List in Comparison Source: https://sourcegraph.com/docs/code-search/compare-file-filtering.md Example URL demonstrating the use of a `compressedFileList` parameter for including a large number of files in the comparison. ```bash ?compressedFileList=H4sIAAAAAAAAA2NgYGBg... ```