Zum Inhalt

Quellegraph Cheat Blatt

_

_

Im Überblick

Sourcegraph ist eine universelle Codesuche und Navigationsplattform, die Entwicklern hilft, Änderungen über ihre gesamte Codebase zu verstehen, zu beheben und zu automatisieren. Es bietet semantische Codesuche, Cross-Repository-Navigation und Code Intelligence für Teams, die mit großen, verteilten Codebases arbeiten.

ZEITSCHRIFTEN Note: Erhältlich als Cloud-Service (sourcegraph.com) oder selbstgehostete Bereitstellung. Free tier verfügbar mit Nutzungslimits.

Installation und Inbetriebnahme

Cloud Service

```bash

Access Sourcegraph Cloud

Visit: https://sourcegraph.com

Sign up with GitHub, GitLab, or email

Connect repositories for indexing

```_

Selbstbefriedigung

```bash

Docker Compose deployment

git clone https://github.com/sourcegraph/deploy-sourcegraph-docker.git cd deploy-sourcegraph-docker docker-compose up -d

Kubernetes deployment

kubectl apply -f https://raw.githubusercontent.com/sourcegraph/deploy-sourcegraph/master/base/sourcegraph.yaml

Single container (development)

docker run -d \ --name sourcegraph \ -p 7080:7080 \ -v ~/.sourcegraph/config:/etc/sourcegraph \ -v ~/.sourcegraph/data:/var/opt/sourcegraph \ sourcegraph/server:latest ```_

Browser Extensions

```bash

Chrome/Edge extension

Visit Chrome Web Store

Search "Sourcegraph"

Install browser extension

Firefox extension

Visit Firefox Add-ons

Search "Sourcegraph"

Install extension

```_

Suche Syntax

Grundlegende Suche

```bash

Simple text search

hello world

Case-sensitive search

case:yes Hello World

Regular expression search

/func\s+\w+(/

Exact match

"exact phrase" ```_

Repository Filter

```bash

Search in specific repository

repo:github.com/facebook/react useState

Search in multiple repositories

repo:facebook/react|vue/vue useState

Exclude repositories

-repo:test-repo main function

Search by repository pattern

repo:.*-frontend$ component ```_

Dateifilter

```bash

Search in specific file types

file:.js$ function

Search in specific files

file:package.json dependencies

Exclude file types

-file:.test.js$ function

Search in file paths

file:src/components/ useState ```_

Sprachenfilter

```bash

Search in specific language

lang:javascript async function

Search in multiple languages

lang:python|go|rust error handling

Exclude languages

-lang:test function definition ```_

Inhalt Filter

```bash

Search function definitions

type:symbol function_name

Search for commits

type:commit bug fix

Search for diffs

type:diff added new feature

Search symbols only

type:symbol class MyClass ```_

In den Warenkorb

Strukturelle Suche

```bash

Find function calls with patterns

:func

Find if statements

if (:[condition]) { :[body] }

Find class definitions

class :[name] extends :[parent] { :[body] }

Find import statements

import :[imports] from ':[module]' ```_

Zeitbasierte Suche

```bash

Search commits after date

type:commit after:"2024-01-01" security fix

Search commits before date

type:commit before:"2024-12-31" refactor

Search commits in date range

type:commit after:"2024-01-01" before:"2024-06-30" feature ```_

Autor and Commit Filters

```bash

Search by commit author

type:commit author:john.doe bug fix

Search by committer

type:commit committer:jane.smith merge

Search commit messages

type:commit message:"breaking change"

Search by commit hash

type:commit 7f8a9b2c ```_

Boolean Operators

```bash

AND operator (default)

function AND async

OR operator

function OR method

NOT operator

function NOT test

Grouping with parentheses

(function OR method) AND async ```_

Code Intelligence

Zur Definition

```bash

Navigate to symbol definition

Click on symbol in code view

Or use Ctrl+Click (with browser extension)

Find all references

Right-click on symbol

Select "Find references"

```_

Cross-Repository Navigation

```bash

Find implementations across repos

Search for interface or abstract class

View implementations in different repositories

Trace dependencies

Click on import statements

Navigate to source in external repositories

```_

```bash

Find symbol definitions

type:symbol MyClass

Find symbols by type

type:symbol function getUserData

Find symbols in specific repository

repo:myorg/myrepo type:symbol ApiClient ```_

• Browsererweiterung

GitHub Integration

```bash

Features on GitHub:

- Code intelligence on files

- Go to definition

- Find references

- Search across repositories

- Hover tooltips for symbols

```_

GitLab Integration ```bash

Features on GitLab:

- Code navigation

- Symbol definitions

- Cross-repository search

- Merge request code intelligence

```_

Konfiguration

```bash

Extension settings:

1. Click extension icon

2. Configure Sourcegraph URL

3. Set authentication token

4. Enable/disable features

```_

Die API Verwendung

Abbildung QL API

```bash

API endpoint

https://sourcegraph.com/.api/graphql

Authentication header

Authorization: token YOUR_ACCESS_TOKEN ```_

Search API

graphql query SearchQuery($query: String!) { search(query: $query) { results { results { ... on FileMatch { file { path repository { name } } lineMatches { lineNumber line } } } } } }_

Repository API

graphql query RepositoryQuery($name: String!) { repository(name: $name) { name url description defaultBranch { name } commit(rev: "HEAD") { oid message } } }_

cURL Beispiele

```bash

Search repositories

curl -X POST \ -H "Authorization: token YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{"query": "query { search(query: \"repo:myorg/myrepo function\") { results { results { __typename } } } }"}' \ https://sourcegraph.com/.api/graphql

Get repository information

curl -X POST \ -H "Authorization: token YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{"query": "query { repository(name: \"github.com/facebook/react\") { name description } }"}' \ https://sourcegraph.com/.api/graphql ```_

CLI Tool

Installation

```bash

Install Sourcegraph CLI

macOS

brew install sourcegraph/src-cli/src-cli

Linux

curl -L https://github.com/sourcegraph/src-cli/releases/download/3.43.2/src-cli_3.43.2_linux_amd64.tar.gz | tar xz sudo mv src /usr/local/bin/

Windows

Download from GitHub releases

Add to PATH

```_

Authentication

```bash

Configure CLI

src login https://sourcegraph.com

Set access token

src config set endpoint https://sourcegraph.com src config set access-token YOUR_ACCESS_TOKEN

Verify configuration

src config get ```_

Search Commands

```bash

Basic search

src search "function useState"

Search with filters

src search "repo:facebook/react useState"

Output as JSON

src search -json "async function"

Search with context

src search -context 3 "error handling" ```_

Repository Management

```bash

List repositories

src repos list

Add repository

src repos add github.com/myorg/myrepo

Remove repository

src repos remove github.com/myorg/myrepo

Sync repository

src repos sync github.com/myorg/myrepo ```_

(Batch ändert sich)

Batch-Änderungen erstellen

```bash

Create batch change spec

cat > batch-change.yaml << EOF name: update-dependencies description: Update package.json dependencies on: - repositoriesMatchingQuery: file:package.json steps: - run: npm update container: node:16 - run: npm audit fix container: node:16 changesetTemplate: title: Update npm dependencies body: | This batch change updates npm dependencies to their latest versions and fixes security vulnerabilities. branch: update-dependencies commit: message: Update npm dependencies and fix security issues published: false EOF

Apply batch change

src batch apply -f batch-change.yaml ```_

Verwaltung von Batch Changes

```bash

List batch changes

src batch list

Preview batch change

src batch preview -f batch-change.yaml

Apply batch change

src batch apply -f batch-change.yaml

Close batch change

src batch close BATCH_CHANGE_ID ```_

Batch Change Beispiele

```yaml

Update copyright headers

name: update-copyright description: Update copyright year in all files on: - repositoriesMatchingQuery: file:.js$ OR file:.py$ OR file:.go$ steps: - run: | find . -name ".js" -o -name ".py" -o -name "*.go" | \ xargs sed -i 's/Copyright 2023/Copyright 2024/g' container: alpine:latest changesetTemplate: title: Update copyright year to 2024 body: Automated update of copyright year from 2023 to 2024 branch: update-copyright-2024 commit: message: Update copyright year to 2024 ```_

• Code Monitoring

Einrichten von Monitoren

```bash

Create code monitor

1. Go to Sourcegraph web interface

2. Navigate to Code Monitoring

3. Click "Create monitor"

4. Define search query

5. Set notification preferences

```_

Beispiele überwachen

```bash

Monitor for security vulnerabilities

query: "TODO.*security|FIXME.*vulnerability" description: "Track security-related TODOs and FIXMEs"

Monitor for deprecated API usage

query: "deprecated.*api|legacy.*function" description: "Track usage of deprecated APIs"

Monitor for performance issues

query: "slow.*query|performance.*issue" description: "Track performance-related comments" ```_

Notifications

```bash

Supported notification channels:

- Email

- Slack

- Microsoft Teams

- Webhook

- PagerDuty

```_

Insights

Insights erstellen

```bash

Language distribution insight

{ "title": "Language Distribution", "type": "lang-stats", "repositories": ["github.com/myorg/myrepo"], "series": [ { "name": "JavaScript", "query": "lang:javascript", "stroke": "#f1e05a" }, { "name": "Python", "query": "lang:python", "stroke": "#3572A5" } ] } ```_

Migration Tracking

```bash

Track migration progress

{ "title": "React Class to Hooks Migration", "type": "search-based", "repositories": ["github.com/myorg/frontend"], "series": [ { "name": "Class Components", "query": "class.extends.*Component", "stroke": "#ff0000" }, { "name": "Functional Components", "query": "const.=.\(.\).=>|function.\(", "stroke": "#00ff00" } ] } ```_

• Unternehmensmerkmale

SAML/SSO Integration

```bash

Configure SAML authentication

1. Admin panel > Authentication

2. Enable SAML

3. Configure identity provider

4. Set attribute mappings

5. Test authentication

```_

Repository Berechtigungen

```bash

Sync permissions from code host

GitHub: Uses repository visibility and team permissions

GitLab: Uses project visibility and group permissions

Bitbucket: Uses repository permissions

Manual permission configuration

Admin panel > Repositories > Permissions

Set user/team access levels

```_

Audit Logging

```bash

Enable audit logging

Admin panel > Audit log

Configure log retention

Export logs for compliance

Log events include:

- User authentication

- Repository access

- Search queries

- Configuration changes

```_

 Leistungsoptimierung

Search Performance

```bash

Optimize search queries:

- Use specific repository filters

- Limit file type searches

- Use structural search for complex patterns

- Avoid overly broad regex patterns

```_

Index Management

```bash

Repository indexing status

Admin panel > Repositories

View indexing progress

Force re-indexing if needed

Index configuration

Adjust indexing frequency

Set resource limits

Configure language servers

```_

Scaling Betrachtungen

```bash

Horizontal scaling:

- Multiple frontend instances

- Separate search backend

- Distributed indexing

- Load balancing

Resource requirements:

- CPU: 4+ cores per 1000 repositories

- Memory: 8GB+ per instance

- Storage: SSD recommended for indexes

```_

Fehlerbehebung

Häufige Fragen

```bash

Search not returning results:

1. Check repository indexing status

2. Verify search syntax

3. Check repository permissions

4. Review filter settings

Slow search performance:

1. Use more specific queries

2. Add repository filters

3. Check system resources

4. Review index health

```_

Debug Information

```bash

Enable debug logging

Admin panel > Monitoring

Set log level to debug

Check application logs

Search debug info

Add &trace=1 to search URL

View query execution details

Analyze performance metrics

```_

Health Checks

```bash

System health endpoints

curl https://sourcegraph.com/-/healthz

Repository sync status

curl https://sourcegraph.com/-/debug/repos

Search backend status

curl https://sourcegraph.com/-/debug/search ```_

oder Best Practices

Suchstrategien

```bash

Start broad, then narrow:

1. Begin with general terms

2. Add repository filters

3. Refine with file types

4. Use structural search for precision

Use appropriate search types:

- Text search for general queries

- Symbol search for definitions

- Structural search for patterns

- Commit search for history

```_

Repository Organization

```bash

Organize repositories logically:

- Group related repositories

- Use consistent naming conventions

- Tag repositories by team/project

- Set appropriate permissions

```_

Team Adoption

```bash

Encourage team usage:

- Provide training sessions

- Share useful search patterns

- Create documentation

- Set up monitoring for common issues

- Integrate with existing workflows

```_

Ressourcen

Dokumentation

Community

Training