Merge branch 'main' into preview
This commit is contained in:
commit
af3d3cdc67
50 changed files with 7532 additions and 12602 deletions
52
.github/workflows/main.yaml
vendored
52
.github/workflows/main.yaml
vendored
|
|
@ -85,6 +85,9 @@ jobs:
|
|||
run: |
|
||||
cd extensions/vscode
|
||||
npm ci
|
||||
env:
|
||||
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
|
||||
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
|
||||
|
||||
- name: Install gui Dependencies
|
||||
run: |
|
||||
|
|
@ -96,31 +99,22 @@ jobs:
|
|||
cd core
|
||||
npm ci --legacy-peer-deps
|
||||
|
||||
# 2.5. Pre package and download anything that needs to be built on Apple Silicon
|
||||
- name: Prepare the extension
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
npm run prepackage
|
||||
|
||||
- name: Make the out directory
|
||||
if: matrix.os == 'macos-latest' && matrix.arch == 'arm64'
|
||||
# 2.5. Pre package
|
||||
- name: Make the out/node_modules directory
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
mkdir out
|
||||
cd out
|
||||
mkdir node_modules
|
||||
|
||||
- name: Download node_modules for esbuild on Apple Silicon
|
||||
if: matrix.os == 'macos-latest' && matrix.arch == 'arm64'
|
||||
run: curl -o extensions/vscode/out/node_modules.zip https://continue-server-binaries.s3.us-west-1.amazonaws.com/node_modules.zip
|
||||
- name: Set var for environment info
|
||||
shell: pwsh
|
||||
run: echo "target=${{ matrix.platform }}-${{ matrix.arch }}" >> $env:GITHUB_ENV
|
||||
|
||||
- name: Unzip node_modules for esbuild on Apple Silicon
|
||||
if: matrix.os == 'macos-latest' && matrix.arch == 'arm64'
|
||||
- name: Prepackage the extension
|
||||
run: |
|
||||
cd extensions/vscode/out
|
||||
unzip node_modules.zip
|
||||
|
||||
- name: Remove node_modules.zip for esbuild on Apple Silicon
|
||||
if: matrix.os == 'macos-latest' && matrix.arch == 'arm64'
|
||||
run: rm extensions/vscode/out/node_modules.zip
|
||||
cd extensions/vscode
|
||||
npm run prepackage -- --target ${{ env.target }}
|
||||
|
||||
# 3. Run tests for the extension
|
||||
|
||||
|
|
@ -140,9 +134,13 @@ jobs:
|
|||
# if: matrix.os != 'ubuntu-latest'
|
||||
|
||||
# 4. Package the extension
|
||||
- shell: pwsh
|
||||
run: echo "target=${{ matrix.platform }}-${{ matrix.arch }}" >> $env:GITHUB_ENV
|
||||
- run: cd extensions/vscode && npx vsce package --target ${{ env.target }}
|
||||
- name: Re-install esbuild
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
npm install -f esbuild
|
||||
|
||||
- name: Package the extension
|
||||
run: cd extensions/vscode && npx vsce package --target ${{ env.target }}
|
||||
|
||||
# 5. Upload the .vsix as an artifact
|
||||
- uses: actions/upload-artifact@v2
|
||||
|
|
@ -150,14 +148,6 @@ jobs:
|
|||
name: ${{ env.target }}
|
||||
path: "extensions/vscode/*.vsix"
|
||||
|
||||
# 6. Upload continue.log as an artifact for debugging of the workflow
|
||||
- name: Upload continue.log
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: continue-log
|
||||
path: /home/runner/.continue/continue.log
|
||||
if: always()
|
||||
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
|
|
@ -214,7 +204,7 @@ jobs:
|
|||
|
||||
# 5 Send to Discord Webhook
|
||||
- name: Discord Commits
|
||||
uses: Sniddl/discord-commits@v1.6
|
||||
uses: Sniddl/discord-commits@1.7
|
||||
with:
|
||||
webhook: ${{ secrets.DISCORD_WEBHOOK }}
|
||||
template: "avatar-with-link"
|
||||
|
|
|
|||
8
.github/workflows/preview.yaml
vendored
8
.github/workflows/preview.yaml
vendored
|
|
@ -143,14 +143,6 @@ jobs:
|
|||
name: ${{ env.target }}
|
||||
path: "extensions/vscode/*.vsix"
|
||||
|
||||
# 6. Upload continue.log as an artifact for debugging of the workflow
|
||||
- name: Upload continue.log
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: continue-log
|
||||
path: /home/runner/.continue/continue.log
|
||||
if: always()
|
||||
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
|
|
|
|||
|
|
@ -8,15 +8,13 @@ keywords: [context, "@", provider, LLM]
|
|||
|
||||
Context Providers allow you to type '@' and see a dropdown of content that can all be fed to the LLM as context. Every context provider is a plugin, which means if you want to reference some source of information that you don't see here, you can request (or build!) a new context provider.
|
||||
|
||||
As an example, say you are working on solving a new GitHub Issue. You type '@issue' and select the one you are working on. Continue can now see the issue title and contents. You also know that the issue is related to the files 'readme.md' and 'helloNested.py', so you type '@readme' and '@hello' to find and select them. Now these 3 "Context Items" are displayed above the input.
|
||||
As an example, say you are working on solving a new GitHub Issue. You type '@issue' and select the one you are working on. Continue can now see the issue title and contents. You also know that the issue is related to the files 'readme.md' and 'helloNested.py', so you type '@readme' and '@hello' to find and select them. Now these 3 "Context Items" are displayed inline with the rest of your input.
|
||||
|
||||

|
||||
|
||||
When you enter your next input, Continue will see the full contents of each of these items, and can use them to better answer your questions throughout the conversation.
|
||||
|
||||
## Built-in Context Providers
|
||||
|
||||
To use any of the built-in context providers, open `~/.continue/config.json` (can do this with the '/config' slash command) and add it to the `contextProviders` list.
|
||||
To use any of the built-in context providers, open `~/.continue/config.json` and add it to the `contextProviders` list.
|
||||
|
||||
### Git Diff
|
||||
|
||||
|
|
@ -36,34 +34,39 @@ Type '@terminal' to reference the contents of your IDE's terminal.
|
|||
|
||||
### Open Files
|
||||
|
||||
Type '@open' to reference the contents of all of your open files.
|
||||
Type '@open' to reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
|
||||
|
||||
```json
|
||||
{ "name": "open" }
|
||||
{ "name": "open", "params": { "onlyPinned": true } }
|
||||
```
|
||||
|
||||
### Codebase Search
|
||||
### Codebase Retrieval
|
||||
|
||||
Type '@search' to reference the results of codebase search, just like the results you would get from VS Code search.
|
||||
Type '@codebase' to automatically retrieve the most relevant snippets from your codebase. Read more about indexing and retrieval [here](../walkthroughs/codebase-embeddings.md).
|
||||
|
||||
```json
|
||||
{ "name": "codebase" }
|
||||
```
|
||||
|
||||
### Folders
|
||||
|
||||
Type '@folder' to use the same retrieval mechanism as '@codebase', but only on a single folder.
|
||||
|
||||
```json
|
||||
{ "name": "folder" }
|
||||
```
|
||||
|
||||
### Exact Search
|
||||
|
||||
Type '@search' to reference the results of codebase search, just like the results you would get from VS Code search. This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep).
|
||||
|
||||
```json
|
||||
{ "name": "search" }
|
||||
```
|
||||
|
||||
### URLs
|
||||
|
||||
Type '@url' to reference the contents of a URL. You can either reference preset URLs, or reference one dynamically by typing '@url https://example.com'. The text contents of the page will be fetched and used as context.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "url",
|
||||
"params": { "presetUrls": ["https://continue.dev/docs/customization"] }
|
||||
}
|
||||
```
|
||||
|
||||
### File Tree
|
||||
|
||||
Type '@tree' to reference the contents of your current workspace. The LLM will be able to see the nested directory structure of your project.
|
||||
Type '@tree' to reference the structure of your current workspace. The LLM will be able to see the nested directory structure of your project.
|
||||
|
||||
```json
|
||||
{ "name": "tree" }
|
||||
|
|
@ -84,7 +87,7 @@ Note: You can get an API key for free at [serper.dev](https://serper.dev).
|
|||
|
||||
### GitHub Issues
|
||||
|
||||
Type '@issue' to reference the conversation inside of a GitHub issue.
|
||||
Type '@issue' to reference the conversation in a GitHub issue. Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited:
|
||||
|
||||
```json
|
||||
{
|
||||
|
|
@ -96,7 +99,7 @@ Type '@issue' to reference the conversation inside of a GitHub issue.
|
|||
"repo": "continue"
|
||||
}
|
||||
],
|
||||
"githubToken": "<my_github_auth_token>"
|
||||
"githubToken": "ghp_xxx"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -107,6 +110,8 @@ Not seeing what you want? Create an issue [here](https://github.com/continuedev/
|
|||
|
||||
## Building Your Own Context Provider
|
||||
|
||||
> Currently custom context providers are only supported in VS Code, but are coming soon to JetBrains IDEs.
|
||||
|
||||
### Introductory Example
|
||||
|
||||
To write your own context provider, you just have to implement the `CustomContextProvider`
|
||||
|
|
@ -117,20 +122,26 @@ interface CustomContextProvider {
|
|||
title: string;
|
||||
displayTitle?: string;
|
||||
description?: string;
|
||||
getContextItems(query: string, fullInput: string): Promise<ContextItem[]>;
|
||||
getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
): Promise<ContextItem[]>;
|
||||
}
|
||||
```
|
||||
|
||||
As an example, let's say you have a set of internal documents that have been indexed in a vector database. You've set up a simple REST API that allows internal users to query and get back relevant snippets. This context provider will send the query to this server and return the results from the vector database.
|
||||
|
||||
```typescript
|
||||
const RagContextProvider = {
|
||||
```typescript title="~/.continue/config.ts"
|
||||
const RagContextProvider: CustomContextProvider = {
|
||||
title: "rag",
|
||||
displayTitle: "RAG",
|
||||
description:
|
||||
"Retrieve snippets from our vector database of internal documents",
|
||||
|
||||
getContextItems: async (query: string, fullInput: string) => {
|
||||
getContextItems: async (
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
): Promise<ContextItem[]> => {
|
||||
const response = await fetch("https://internal_rag_server.com/retrieve", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ query }),
|
||||
|
|
@ -139,7 +150,7 @@ const RagContextProvider = {
|
|||
const results = await response.json();
|
||||
|
||||
return results.map((result) => ({
|
||||
title: result.title,
|
||||
name: result.title,
|
||||
description: result.title,
|
||||
content: result.contents,
|
||||
}));
|
||||
|
|
@ -151,7 +162,32 @@ It can then be added in `config.ts` like so:
|
|||
|
||||
```typescript title="~/.continue/config.ts"
|
||||
export function modifyConfig(config: Config): Config {
|
||||
config.contextProviders.append(RagContextProvider);
|
||||
if (!config.contextProviders) {
|
||||
config.contextProviders = [];
|
||||
}
|
||||
config.contextProviders.push(RagContextProvider);
|
||||
return config;
|
||||
}
|
||||
```
|
||||
|
||||
No modification in `config.json` is necessary.
|
||||
|
||||
### Importing outside modules
|
||||
|
||||
> Context providers run in a NodeJS environment, but for the time being the `modifyConfig` function will be called both from NodeJS _and_ the browser. This means that if you are importing packages requiring NodeJS, you should dynamically import them inside of the context provider (e.g. `const moduleA = await import('./moduleA');`).
|
||||
|
||||
To include outside Node modules in your config.ts, run `npm install <module_name>` from the `~/.continue` directory, and then import them in config.ts.
|
||||
|
||||
Continue will use [esbuild](https://esbuild.github.io/) to bundle your `config.ts` and any dependencies into a single Javascript file. The exact configuration used can be found [here](https://github.com/continuedev/continue/blob/5c9874400e223bbc9786a8823614a2e501fbdaf7/extensions/vscode/src/ideProtocol.ts#L45-L52).
|
||||
|
||||
### `CustomContextProvider` Reference
|
||||
|
||||
- `title`: An identifier for the context provider
|
||||
- `displayTitle` (optional): The title displayed in the dropdown
|
||||
- `description` (optional): The longer description displayed in the dropdown when hovered
|
||||
- `getContextItems`: A function that returns the documents to include in the prompt. It should return a list of `ContextItem`s, and is given access to the following arguments:
|
||||
- `extras.fullInput`: A string representing the user's full input to the text box. This can be used for example to generate an embedding to compare against a set of other embedded documents
|
||||
- `extras.embeddingsProvider`: The embeddings provider has an `embed` function that will convert text (such as `fullInput`) to an embedding
|
||||
- `extras.llm`: The current default LLM, which you can use to make completion requests
|
||||
- `extras.ide`: An instance of the `IDE` class, which lets you gather various sources of information from the IDE, including the contents of the terminal, the list of open files, or any warnings in the currently open file.
|
||||
- `query`: (not currently used) A string representing the query
|
||||
|
|
|
|||
|
|
@ -6,13 +6,13 @@ keywords: [temperature, custom policies, custom system message]
|
|||
|
||||
# Other Configuration
|
||||
|
||||
See the [ContinueConfig Reference](../reference/config) for the full list of configuration options.
|
||||
See the [config.json Reference](../reference/config) for the full list of configuration options.
|
||||
|
||||
## Customize System Message
|
||||
|
||||
You can write your own system message, a set of instructions that will always be top-of-mind for the LLM, by setting the `systemMessage` property to any string. For example, you might request "Please make all responses as concise as possible and never repeat something you have already explained."
|
||||
|
||||
System messages can also reference files. For example, if there is a markdown file (e.g. at `/Users/nate/Documents/docs/reference.md`) you'd like the LLM to know about, you can reference it with [Mustache](http://mustache.github.io/mustache.5.html) templating like this: "Please reference this documentation: {{ Users/nate/Documents/docs/reference.md }}". As of now, you must use an absolute path.
|
||||
System messages can also reference files. For example, if there is a markdown file (e.g. at `/Users/nate/Documents/docs/reference.md`) you'd like the LLM to know about, you can reference it with [Mustache](http://mustache.github.io/mustache.5.html) templating like this: "Please reference this documentation: \{\{ Users/nate/Documents/docs/reference.md \}\}". As of now, you must use an absolute path.
|
||||
|
||||
## Temperature
|
||||
|
||||
|
|
|
|||
|
|
@ -11,6 +11,6 @@ Continue can be deeply customized by editing `~/.continue/config.json` (`%userpr
|
|||
Currently, you can customize the following:
|
||||
|
||||
- [Models](../model-setup/select-model.md) and [providers](../model-setup/select-provider.md)
|
||||
- [Context Providers](./context-providers.md) - Just type '@' to easily add attachments to your prompt. Define which sources you want to easily reference, including GitHub Issues, terminal output, and preset URLs.
|
||||
- [Context Providers](./context-providers.md) - Type '@' to easily add attachments to your prompt. Define which sources you want to reference, including GitHub Issues, terminal output, or automatically retrieved snippets from your codebase.
|
||||
- [Slash Commands](./slash-commands.md) - Call custom prompts or programs written with our SDK by typing `/`.
|
||||
- [Other Configuration](./other-configuration.md) - Configure other settings like the system message and temperature.
|
||||
- [Other Configuration](../reference/config.mdx) - Configure other settings like the system message and temperature.
|
||||
|
|
|
|||
|
|
@ -6,14 +6,112 @@ keywords: [slash command, custom commands, step]
|
|||
|
||||
# Slash Commands
|
||||
|
||||
Slash commands are shortcuts that can be activated by prefacing your input with '/'. For example, the built-in '/edit' slash command let you stream edits directly into your editor.
|
||||
Slash commands are shortcuts that can be activated by typing '/' and selecting from the dropdown. For example, the built-in '/edit' slash command let you stream edits directly into your editor.
|
||||
|
||||

|
||||
|
||||
## Built-in Slash Commands
|
||||
|
||||
To use any of the built-in slash commands, open `~/.continue/config.json` and add it to the `slashCommands` list.
|
||||
|
||||
### `/edit`
|
||||
|
||||
Select code with ctrl/cmd + M (VS Code) or ctrl/cmd + J (JetBrains), and then type "/edit", followed by instructions for the edit. Continue will stream the changes into a side-by-side diff editor.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "edit",
|
||||
"description": "Edit highlighted code"
|
||||
}
|
||||
```
|
||||
|
||||
### `/comment`
|
||||
|
||||
Comment works just like /edit, except it will automatically prompt the LLM to comment the code.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "comment",
|
||||
"description": "Write comments for the highlighted code"
|
||||
}
|
||||
```
|
||||
|
||||
### `/share`
|
||||
|
||||
Type "/share" to generate a shareable markdown transcript of your current chat history.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "share",
|
||||
"description": "Download and share this session"
|
||||
}
|
||||
```
|
||||
|
||||
### `/cmd`
|
||||
|
||||
Generate a shell command from natural language and (only in VS Code) automatically paste it into the terminal.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "cmd",
|
||||
"description": "Generate a shell command"
|
||||
}
|
||||
```
|
||||
|
||||
### `/commit`
|
||||
|
||||
Shows the LLM your current git diff and asks it to generate a commit message.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "commit",
|
||||
"description": "Generate a commit message for the current changes"
|
||||
}
|
||||
```
|
||||
|
||||
### `/http`
|
||||
|
||||
Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup. The endpoint should return a sequence of string updates, which will be streamed to the Continue sidebar. See our basic [FastAPI example](https://github.com/continuedev/continue/blob/74002369a5e435735b83278fb965e004ae38a97d/core/context/providers/context_provider_server.py#L34-L45) for reference.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "http",
|
||||
"description": "Does something custom",
|
||||
"params": { "url": "<my server endpoint>" }
|
||||
}
|
||||
```
|
||||
|
||||
### `/issue`
|
||||
|
||||
Describe the issue you'd like to generate, and Continue will turn into a well-formatted title and body, then give you a link to the draft so you can submit. Make sure to set the URL of the repository you want to generate issues for.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "issue",
|
||||
"description": "Generate a link to a drafted GitHub issue",
|
||||
"params": { "repositoryUrl": "https://github.com/continuedev/continue" }
|
||||
}
|
||||
```
|
||||
|
||||
### `/so`
|
||||
|
||||
The StackOverflow slash command will automatically pull results from StackOverflow to answer your question, quoting links along with its answer.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "so",
|
||||
"description": "Reference StackOverflow to answer the question"
|
||||
}
|
||||
```
|
||||
|
||||
## Custom Slash Commands
|
||||
|
||||
There are two ways to add custom slash commands:
|
||||
|
||||
1. With natural language prompts - this is simpler and only requires writing a string or string template.
|
||||
2. With a custom function - this gives you full access to the Continue SDK and allows you to write arbitrary Typescript code.
|
||||
|
||||
## "Custom Commands" (Use Natural Language)
|
||||
### "Custom Commands" (Use Natural Language)
|
||||
|
||||
You can add custom slash commands by adding to the `customCommands` property in `config.json`.
|
||||
|
||||
|
|
@ -31,7 +129,7 @@ customCommands=[{
|
|||
}]
|
||||
```
|
||||
|
||||
## Custom Slash Commands
|
||||
### Custom Slash Commands
|
||||
|
||||
If you want to go a step further than writing custom commands with natural language, you can write a custom function that returns the response. This requires using `config.ts` instead of `config.json`.
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
---
|
||||
title: Development data
|
||||
title: 🧑💻 Development data
|
||||
description: Collecting data on how you build software
|
||||
keywords: [development data, dev data, LLM-aided development]
|
||||
---
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
---
|
||||
title: How to use Continue
|
||||
title: 🧑🎓 How to use Continue
|
||||
description: Using LLMs as you code with Continue
|
||||
keywords: [how to, edit, refactor, boilerplate, context]
|
||||
---
|
||||
|
|
|
|||
|
|
@ -1,15 +1,25 @@
|
|||
---
|
||||
title: Introduction
|
||||
title: 💻 Introduction
|
||||
description: Continue is the open-source autopilot for software development
|
||||
keywords: [introduction, intro, continue, autopilot, chatgpt]
|
||||
---
|
||||
|
||||
# Introduction
|
||||
# 💻 Introduction
|
||||
|
||||

|
||||
|
||||
**Continue is an open-source autopilot for [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)—the easiest way to code with any LLM**
|
||||
|
||||
You determine when Large Language Models (LLMs) like [GPT-4](https://openai.com/research/gpt-4) and [Code Llama](https://about.fb.com/news/2023/08/code-llama-ai-for-coding/) should act as an autopilot, helping you complete software development tasks. You highlight some code and then use natural language instructions (and optional slash commands like `/edit`) to tell the LLM what to do.
|
||||
Many developers have begun to use ChatGPT while coding; however, the experience is painful because of how much copying, pasting, and editing is required to provide the context and incorporate the generated answers into your codebase. Continue eliminates this pain by enabling LLMs to act natively in your IDE as you complete your workflows.
|
||||
|
||||
Many developers have begun to use ChatGPT while coding; however, the experience is painful because of how much copying, pasting, and editing is required to provide the context and incorporate the generated answers into your codebase. Continue eliminates this pain by enabling LLMs to natively act in your IDE as you complete your workflows.
|
||||
Some examples of what you can achieve are:
|
||||
|
||||
- Use cmd/ctrl + shift + L to generate boilerplate code from natural language
|
||||
- Highlight code, describe how to refactor it, and have changes streamed into your editor
|
||||
- Ask high-level questions about your codebase, with Continue automatically finding relevant files
|
||||
- Quickly generate unit tests for any function or class
|
||||
- Ask a quick question to get immediate answers without leaving your editor
|
||||
- Have your current changes reviewed for mistakes that the compiler can't catch
|
||||
- Type '@' to reference dozens of different sources while communicating with the LLM
|
||||
|
||||
Continue lets you do all of this with any LLM, whether open-source, commercial, local, or remote. And we provide numerous points of configuration so that you can customize the extension to fit into your existing workflows.
|
||||
|
|
|
|||
|
|
@ -1,18 +1,20 @@
|
|||
# Overview
|
||||
|
||||
Continue is the easiest way to code with any [Large Language Model (LLM)](https://www.youtube.com/watch?v=zjkBMFhNj_g). You can use it with commercial models like GPT-4 via the OpenAI API, open-source models running on your laptop with Ollama like Code Llama, and everything in between. You have the ability to configure what model you use, what provider you use, and how you use them.
|
||||
Continue is the easiest way to code with any [Large Language Model (LLM)](https://www.youtube.com/watch?v=zjkBMFhNj_g). You can use it with commercial models like GPT-4 via the OpenAI API, open-source models like CodeLlama running on your laptop with Ollama, and everything in between.
|
||||
|
||||
When you first install Continue, you can try it out for free using a proxy server that securely makes calls with our API key to models like GPT-4, Gemini Pro, and Phind CodeLlama via OpenAI, Google, and Together respectively.
|
||||
When you first install Continue, you can try it out for free using a proxy server that securely makes calls with our API keys to models like GPT-4, Gemini Pro, and Phind CodeLlama via OpenAI, Google, and Together respectively.
|
||||
|
||||
Once you're ready to use your own API key or a different model / provider, press the `+` button in the bottom left to add a new model to your `config.json`.
|
||||
|
||||
If you are unsure what model or provider to use, here is a rule of thumb:
|
||||
|
||||
- Use GPT-4 via OpenAI if you want the best possible model overall right now
|
||||
- Use X via Together if you want the best open-source model right now
|
||||
- Use X via Ollama if you want to run a model locally on Mac or Linux
|
||||
- Use X via LM Studio if you want to run a model locally on Windows
|
||||
|
||||
Learn more:
|
||||
|
||||
- [Select a provider](select-provider.md)
|
||||
- [Select a model](select-model.md)
|
||||
- [Configuration](configuration.md)
|
||||
- [Configuration](configuration.md)
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ Continue makes it easy to swap out different LLMs. You can either click the "+"
|
|||
## Open-source LLMs
|
||||
|
||||
The default models available in the GUI:
|
||||
|
||||
- [Code Llama-Instruct-7B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-code-llama)
|
||||
- [Code Llama-Instruct-13B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-code-llama)
|
||||
- [Code Llama-Instruct-34B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-code-llama)
|
||||
|
|
@ -32,15 +33,16 @@ The default models available in the GUI:
|
|||
- [Zephyr-7B](https://huggingface.co/huggingfaceh4/zephyr-7b-beta)
|
||||
- [Neural-Chat-7B](https://huggingface.co/Intel/neural-chat-7b-v3-3)
|
||||
|
||||
**You can also use other open-source models**, but you will need to manually add them to your `config.json`.
|
||||
**You can also use other open-source models**, you just need to manually add them to your `config.json`.
|
||||
|
||||
## Commercial LLMs
|
||||
|
||||
Models available for configuration in the GUI:
|
||||
|
||||
- [GPT-4](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-gpt-4)
|
||||
- [GPT-4-Turbo](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#2-gpt-4-turbo)
|
||||
- [GPT-3.5-Turbo](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#3-gpt-35-turbo)
|
||||
- [Claude-2](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#4-claude-2)
|
||||
- [Gemini Pro](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#5-palm-2)
|
||||
|
||||
**You can also use other commercial models**, but you will need to manually add them to your `config.json`.
|
||||
**You can also use other commercial models**, you just need to manually add them to your `config.json`.
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ You can deploy a model in your [AWS](https://github.com/continuedev/deploy-os-co
|
|||
- [SkyPilot](https://github.com/continuedev/deploy-os-code-llm#skypilot)
|
||||
- [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints) (OpenAI compatible API)
|
||||
|
||||
If the API you use is OpenAI-compatible, you will be able to use the "openai" provider in `config.json` and change the `apiBase` to point to the server. Otherwise, you will need to wire up a new LLM object in `config.ts`. Learn how to do this [here](configuration.md#defining-a-custom-llm-provider)
|
||||
If the API you use is OpenAI-compatible, you will be able to use the "openai" provider in `config.json` and change the `apiBase` to point to the server. Otherwise, you may need to wire up a new LLM object in `config.ts`. Learn how to do this [here](configuration.md#defining-a-custom-llm-provider)
|
||||
|
||||
## SaaS
|
||||
|
||||
|
|
@ -56,4 +56,4 @@ You can use commercial LLMs via APIs using:
|
|||
- [Anthrophic API](../reference/Model%20Providers/anthropicllm.md)
|
||||
- [Google PaLM API](../reference/Model%20Providers/googlepalmapi.md)
|
||||
- [OpenAI free trial](../reference/Model%20Providers/freetrial.md)
|
||||
- [Mistral API](../reference/Model%20Providers/mistral.md)
|
||||
- [Mistral API](../reference/Model%20Providers/mistral.md)
|
||||
|
|
|
|||
|
|
@ -1,17 +1,33 @@
|
|||
---
|
||||
title: Quickstart
|
||||
title: ⚡️ Quickstart
|
||||
description: Getting started with Continue
|
||||
keywords: [quickstart, start, install, vscode, jetbrains]
|
||||
---
|
||||
|
||||
# ⚡️ Quickstart
|
||||
|
||||
## VS Code
|
||||
|
||||
1. Click `Install` on the **[Continue extension in the Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=Continue.continue)**
|
||||
|
||||
2. This will open the Continue extension page in VS Code, where you will need to click `Install` again
|
||||
|
||||
3. Once you do this, you will see the Continue logo show up on the left side bar. If you click it, then the Continue extension will then open up:
|
||||
3. Once you do this, you will see the Continue logo show up on the left side bar. If you click it, the Continue extension will open up:
|
||||
|
||||

|
||||
> We strongly recommend moving Continue to VS Code's right sidebar. This helps keep the file explorer open while using Continue, and the sidebar can be toggled with a simple keyboard shortcut. 
|
||||
|
||||
4. If you have any problems, see the [troubleshooting guide](./troubleshooting.md) or ask for help in [our Discord](https://discord.gg/NWtdYexhMs).
|
||||
|
||||
## JetBrains
|
||||
|
||||
1. Open your JetBrains IDE and open settings using `cmd/ctrl + shift + ,`.
|
||||
|
||||
2. Select **Plugins** on the sidebar.
|
||||
|
||||
3. Search for "Continue" in the marketplace and click `Install`. Once installed you'll see Continue show up on the right toolbar:
|
||||
|
||||

|
||||
|
||||
4. If you have any problems, see the [troubleshooting guide](./troubleshooting.md) or ask for help in [our Discord](https://discord.gg/NWtdYexhMs).
|
||||
|
||||
> Alternatively, you can install from disk after downloading from the [JetBrains Extension Marketplace](https://plugins.jetbrains.com/plugin/22707-continue-extension).
|
||||
|
|
|
|||
|
|
@ -1,21 +0,0 @@
|
|||
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
|
||||
|
||||
# DiffContextProvider
|
||||
|
||||
Type '@diff' to reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing.
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/diff.py)
|
||||
|
||||
## Properties
|
||||
|
||||
<ClassPropertyRef name='workspace_dir' details='{"title": "Workspace Dir", "description": "The workspace directory in which to run `git diff`", "type": "string"}' required={false} default=""/>
|
||||
|
||||
|
||||
### Inherited Properties
|
||||
|
||||
<ClassPropertyRef name='title' details='{"title": "Title", "default": "diff", "type": "string"}' required={false} default="diff"/>
|
||||
<ClassPropertyRef name='ide' details='{"title": "Ide"}' required={false} default=""/>
|
||||
<ClassPropertyRef name='display_title' details='{"title": "Display Title", "default": "Diff", "type": "string"}' required={false} default="Diff"/>
|
||||
<ClassPropertyRef name='description' details='{"title": "Description", "default": "Output of 'git diff' in current repo", "type": "string"}' required={false} default="Output of 'git diff' in current repo"/>
|
||||
<ClassPropertyRef name='dynamic' details='{"title": "Dynamic", "default": true, "type": "boolean"}' required={false} default="True"/>
|
||||
<ClassPropertyRef name='requires_query' details='{"title": "Requires Query", "description": "Indicates whether the ContextProvider requires a query. For example, the SearchContextProvider requires you to type '@search <STRING_TO_SEARCH>'. This will change the behavior of the UI so that it can indicate the expectation for a query.", "default": false, "type": "boolean"}' required={false} default="False"/>
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
|
||||
|
||||
# FileContextProvider
|
||||
|
||||
The FileContextProvider is a ContextProvider that allows you to search files in the open workspace.
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/file.py)
|
||||
|
||||
## Properties
|
||||
|
||||
|
||||
|
||||
### Inherited Properties
|
||||
|
||||
<ClassPropertyRef name='title' details='{"title": "Title", "default": "file", "type": "string"}' required={false} default="file"/>
|
||||
<ClassPropertyRef name='ide' details='{"title": "Ide"}' required={false} default=""/>
|
||||
<ClassPropertyRef name='display_title' details='{"title": "Display Title", "default": "Files", "type": "string"}' required={false} default="Files"/>
|
||||
<ClassPropertyRef name='description' details='{"title": "Description", "default": "Type to search the workspace", "type": "string"}' required={false} default="Type to search the workspace"/>
|
||||
<ClassPropertyRef name='dynamic' details='{"title": "Dynamic", "default": false, "type": "boolean"}' required={false} default="False"/>
|
||||
<ClassPropertyRef name='requires_query' details='{"title": "Requires Query", "description": "Indicates whether the ContextProvider requires a query. For example, the SearchContextProvider requires you to type '@search <STRING_TO_SEARCH>'. This will change the behavior of the UI so that it can indicate the expectation for a query.", "default": false, "type": "boolean"}' required={false} default="False"/>
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
|
||||
|
||||
# FileTreeContextProvider
|
||||
|
||||
Type '@tree' to reference the contents of your current workspace. The LLM will be able to see the nested directory structure of your project.
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/filetree.py)
|
||||
|
||||
## Properties
|
||||
|
||||
<ClassPropertyRef name='workspace_dir' details='{"title": "Workspace Dir", "description": "The workspace directory to display", "type": "string"}' required={false} default=""/>
|
||||
|
||||
|
||||
### Inherited Properties
|
||||
|
||||
<ClassPropertyRef name='title' details='{"title": "Title", "default": "tree", "type": "string"}' required={false} default="tree"/>
|
||||
<ClassPropertyRef name='ide' details='{"title": "Ide"}' required={false} default=""/>
|
||||
<ClassPropertyRef name='display_title' details='{"title": "Display Title", "default": "File Tree", "type": "string"}' required={false} default="File Tree"/>
|
||||
<ClassPropertyRef name='description' details='{"title": "Description", "default": "Add a formatted file tree of this directory to the context", "type": "string"}' required={false} default="Add a formatted file tree of this directory to the context"/>
|
||||
<ClassPropertyRef name='dynamic' details='{"title": "Dynamic", "default": true, "type": "boolean"}' required={false} default="True"/>
|
||||
<ClassPropertyRef name='requires_query' details='{"title": "Requires Query", "description": "Indicates whether the ContextProvider requires a query. For example, the SearchContextProvider requires you to type '@search <STRING_TO_SEARCH>'. This will change the behavior of the UI so that it can indicate the expectation for a query.", "default": false, "type": "boolean"}' required={false} default="False"/>
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
|
||||
|
||||
# GitHubIssuesContextProvider
|
||||
|
||||
The GitHubIssuesContextProvider is a ContextProvider that allows you to search GitHub issues in a repo. Type '@issue' to reference the title and contents of an issue.
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/github.py)
|
||||
|
||||
## Properties
|
||||
|
||||
<ClassPropertyRef name='repo_name' details='{"title": "Repo Name", "description": "The name of the GitHub repo from which to pull issues", "type": "string"}' required={true} default=""/>
|
||||
<ClassPropertyRef name='auth_token' details='{"title": "Auth Token", "description": "The GitHub auth token to use to authenticate with the GitHub API", "type": "string"}' required={true} default=""/>
|
||||
|
||||
|
||||
### Inherited Properties
|
||||
|
||||
<ClassPropertyRef name='title' details='{"title": "Title", "default": "issues", "type": "string"}' required={false} default="issues"/>
|
||||
<ClassPropertyRef name='ide' details='{"title": "Ide"}' required={false} default=""/>
|
||||
<ClassPropertyRef name='display_title' details='{"title": "Display Title", "default": "GitHub Issues", "type": "string"}' required={false} default="GitHub Issues"/>
|
||||
<ClassPropertyRef name='description' details='{"title": "Description", "default": "Reference GitHub issues", "type": "string"}' required={false} default="Reference GitHub issues"/>
|
||||
<ClassPropertyRef name='dynamic' details='{"title": "Dynamic", "default": false, "type": "boolean"}' required={false} default="False"/>
|
||||
<ClassPropertyRef name='requires_query' details='{"title": "Requires Query", "description": "Indicates whether the ContextProvider requires a query. For example, the SearchContextProvider requires you to type '@search <STRING_TO_SEARCH>'. This will change the behavior of the UI so that it can indicate the expectation for a query.", "default": false, "type": "boolean"}' required={false} default="False"/>
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
|
||||
|
||||
# GoogleContextProvider
|
||||
|
||||
Type '@google' to reference the results of a Google search. For example, type "@google python tutorial" if you want to search and discuss ways of learning Python.
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/google.py)
|
||||
|
||||
## Properties
|
||||
|
||||
<ClassPropertyRef name='serper_api_key' details='{"title": "Serper Api Key", "description": "Your SerpAPI key, used to programmatically make Google searches. You can get a key at https://serper.dev.", "type": "string"}' required={true} default=""/>
|
||||
|
||||
|
||||
### Inherited Properties
|
||||
|
||||
<ClassPropertyRef name='title' details='{"title": "Title", "default": "google", "type": "string"}' required={false} default="google"/>
|
||||
<ClassPropertyRef name='ide' details='{"title": "Ide"}' required={false} default=""/>
|
||||
<ClassPropertyRef name='display_title' details='{"title": "Display Title", "default": "Google", "type": "string"}' required={false} default="Google"/>
|
||||
<ClassPropertyRef name='description' details='{"title": "Description", "default": "Search Google", "type": "string"}' required={false} default="Search Google"/>
|
||||
<ClassPropertyRef name='dynamic' details='{"title": "Dynamic", "default": true, "type": "boolean"}' required={false} default="True"/>
|
||||
<ClassPropertyRef name='requires_query' details='{"title": "Requires Query", "default": true, "type": "boolean"}' required={false} default="True"/>
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
|
||||
|
||||
# SearchContextProvider
|
||||
|
||||
Type '@search' to reference the results of codebase search, just like the results you would get from VS Code search.
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/search.py)
|
||||
|
||||
## Properties
|
||||
|
||||
<ClassPropertyRef name='workspace_dir' details='{"title": "Workspace Dir", "description": "The workspace directory to search", "type": "string"}' required={false} default=""/>
|
||||
|
||||
|
||||
### Inherited Properties
|
||||
|
||||
<ClassPropertyRef name='title' details='{"title": "Title", "default": "search", "type": "string"}' required={false} default="search"/>
|
||||
<ClassPropertyRef name='ide' details='{"title": "Ide"}' required={false} default=""/>
|
||||
<ClassPropertyRef name='display_title' details='{"title": "Display Title", "default": "Search", "type": "string"}' required={false} default="Search"/>
|
||||
<ClassPropertyRef name='description' details='{"title": "Description", "default": "Search workspace for exact matches", "type": "string"}' required={false} default="Search workspace for exact matches"/>
|
||||
<ClassPropertyRef name='dynamic' details='{"title": "Dynamic", "default": true, "type": "boolean"}' required={false} default="True"/>
|
||||
<ClassPropertyRef name='requires_query' details='{"title": "Requires Query", "default": true, "type": "boolean"}' required={false} default="True"/>
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
|
||||
|
||||
# TerminalContextProvider
|
||||
|
||||
Type '@terminal' to reference the contents of your IDE's terminal.
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/terminal.py)
|
||||
|
||||
## Properties
|
||||
|
||||
<ClassPropertyRef name='get_last_n_commands' details='{"title": "Get Last N Commands", "description": "The number of previous commands to reference", "default": 3, "type": "integer"}' required={false} default="3"/>
|
||||
|
||||
|
||||
### Inherited Properties
|
||||
|
||||
<ClassPropertyRef name='title' details='{"title": "Title", "default": "terminal", "type": "string"}' required={false} default="terminal"/>
|
||||
<ClassPropertyRef name='ide' details='{"title": "Ide"}' required={false} default=""/>
|
||||
<ClassPropertyRef name='display_title' details='{"title": "Display Title", "default": "Terminal", "type": "string"}' required={false} default="Terminal"/>
|
||||
<ClassPropertyRef name='description' details='{"title": "Description", "default": "Reference the contents of the terminal", "type": "string"}' required={false} default="Reference the contents of the terminal"/>
|
||||
<ClassPropertyRef name='dynamic' details='{"title": "Dynamic", "default": true, "type": "boolean"}' required={false} default="True"/>
|
||||
<ClassPropertyRef name='requires_query' details='{"title": "Requires Query", "description": "Indicates whether the ContextProvider requires a query. For example, the SearchContextProvider requires you to type '@search <STRING_TO_SEARCH>'. This will change the behavior of the UI so that it can indicate the expectation for a query.", "default": false, "type": "boolean"}' required={false} default="False"/>
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
|
||||
|
||||
# URLContextProvider
|
||||
|
||||
Type '@url' to reference the contents of a URL. You can either reference preset URLs, or reference one dynamically by typing '@url https://example.com'. The text contents of the page will be fetched and used as context.
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/url.py)
|
||||
|
||||
## Properties
|
||||
|
||||
<ClassPropertyRef name='preset_urls' details='{"title": "Preset Urls", "description": "A list of preset URLs that you will be able to quickly reference by typing '@url'", "default": [], "type": "array", "items": {"type": "string"}}' required={false} default="[]"/>
|
||||
<ClassPropertyRef name='static_url_context_items' details='{"title": "Static Url Context Items", "default": [], "type": "array", "items": {"$ref": "#/definitions/ContextItem"}}' required={false} default="[]"/>
|
||||
|
||||
|
||||
### Inherited Properties
|
||||
|
||||
<ClassPropertyRef name='title' details='{"title": "Title", "default": "url", "type": "string"}' required={false} default="url"/>
|
||||
<ClassPropertyRef name='ide' details='{"title": "Ide"}' required={false} default=""/>
|
||||
<ClassPropertyRef name='display_title' details='{"title": "Display Title", "default": "URL", "type": "string"}' required={false} default="URL"/>
|
||||
<ClassPropertyRef name='description' details='{"title": "Description", "default": "Reference the contents of a webpage", "type": "string"}' required={false} default="Reference the contents of a webpage"/>
|
||||
<ClassPropertyRef name='dynamic' details='{"title": "Dynamic", "default": true, "type": "boolean"}' required={false} default="True"/>
|
||||
<ClassPropertyRef name='requires_query' details='{"title": "Requires Query", "default": true, "type": "boolean"}' required={false} default="True"/>
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
|
||||
|
||||
# Configuration Options
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/core/config.py)
|
||||
|
||||
## Properties
|
||||
|
||||
<ClassPropertyRef name='disallowed_steps' details='{"title": "Disallowed Steps", "description": "Steps that are not allowed to be run, and will be skipped if attempted", "default": [], "type": "array", "items": {"type": "string"}}' required={false} default="[]"/>
|
||||
<ClassPropertyRef name='allow_anonymous_telemetry' details='{"title": "Allow Anonymous Telemetry", "description": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to False, we will not collect any data.", "default": true, "type": "boolean"}' required={false} default="True"/>
|
||||
<ClassPropertyRef name='models' details='{"title": "Models", "default": [{"title": "GPT-4 (trial)", "provider": "free-trial", "model": "gpt-4", "api_key": "", "api_base": null, "context_length": 2048, "template": null, "completion_options": {"temperature": null, "top_p": null, "top_k": null, "presence_penalty": null, "frequency_penalty": null, "stop": null, "max_tokens": 1023}, "system_message": null, "request_options": {"timeout": 300, "verify_ssl": null, "ca_bundle_path": null, "proxy": null, "headers": null}}], "type": "array", "items": {"$ref": "#/definitions/ModelDescription"}}' required={false} default="[{'title': 'GPT-4 (trial)', 'provider': 'free-trial', 'model': 'gpt-4', 'api_key': '', 'api_base': None, 'context_length': 2048, 'template': None, 'completion_options': {'temperature': None, 'top_p': None, 'top_k': None, 'presence_penalty': None, 'frequency_penalty': None, 'stop': None, 'max_tokens': 1023}, 'system_message': None, 'request_options': {'timeout': 300, 'verify_ssl': None, 'ca_bundle_path': None, 'proxy': None, 'headers': None}}]"/>
|
||||
<ClassPropertyRef name='model_roles' details='{"title": "Model Roles", "description": "Roles for models. Each entry should be the title of a model in the models array.", "default": {"default": "GPT-4 (trial)", "chat": null, "edit": null, "summarize": null}, "allOf": [{"$ref": "#/definitions/ModelRoles"}]}' required={false} default="{'default': 'GPT-4 (trial)', 'chat': None, 'edit': None, 'summarize': None}"/>
|
||||
<ClassPropertyRef name='system_message' details='{"title": "System Message", "description": "A system message that will always be followed by the LLM", "type": "string"}' required={false} default=""/>
|
||||
<ClassPropertyRef name='completion_options' details='{"title": "Completion Options", "description": "Default options for completion. These will be overriden by any options set for a specific model.", "default": {"temperature": null, "top_p": null, "top_k": null, "presence_penalty": null, "frequency_penalty": null, "stop": null, "max_tokens": 1023}, "allOf": [{"$ref": "#/definitions/BaseCompletionOptions"}]}' required={false} default="{'temperature': None, 'top_p': None, 'top_k': None, 'presence_penalty': None, 'frequency_penalty': None, 'stop': None, 'max_tokens': 1023}"/>
|
||||
<ClassPropertyRef name='slash_commands' details='{"title": "Slash Commands", "description": "An array of slash commands that let you map custom Steps to a shortcut.", "default": [], "type": "array", "items": {"$ref": "#/definitions/SlashCommand"}}' required={false} default="[]"/>
|
||||
<ClassPropertyRef name='custom_commands' details='{"title": "Custom Commands", "description": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt.", "default": [{"name": "test", "prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", "description": "This is an example custom command. Use /config to edit it and create more"}], "type": "array", "items": {"$ref": "#/definitions/CustomCommand"}}' required={false} default="[{'name': 'test', 'prompt': "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", 'description': 'This is an example custom command. Use /config to edit it and create more'}]"/>
|
||||
<ClassPropertyRef name='context_providers' details='{"title": "Context Providers", "description": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.", "default": [], "type": "array", "items": {"$ref": "#/definitions/ContextProviderWithParams"}}' required={false} default="[]"/>
|
||||
<ClassPropertyRef name='user_token' details='{"title": "User Token", "description": "An optional token to identify the user.", "type": "string"}' required={false} default=""/>
|
||||
<ClassPropertyRef name='data_server_url' details='{"title": "Data Server Url", "description": "The URL of the server where development data is sent. No data is sent unless you have explicitly set the `user_token` property to a valid token that we have shared.", "default": "https://us-west1-autodebug.cloudfunctions.net", "type": "string"}' required={false} default="https://us-west1-autodebug.cloudfunctions.net"/>
|
||||
<ClassPropertyRef name='disable_summaries' details='{"title": "Disable Summaries", "description": "If set to `True`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.", "default": false, "type": "boolean"}' required={false} default="False"/>
|
||||
<ClassPropertyRef name='disable_indexing' details='{"title": "Disable Indexing", "description": "If set to `True`, Continue will not index the codebase. This is mainly used for debugging purposes.", "default": false, "type": "boolean"}' required={false} default="False"/>
|
||||
<ClassPropertyRef name='retrieval_settings' details='{"title": "Retrieval Settings", "description": "Settings for the retrieval system. Read more about the retrieval system in the documentation.", "default": {"n_retrieve": 50, "n_final": 10, "use_reranking": true, "rerank_group_size": 5, "ignore_files": [], "openai_api_key": null, "api_base": null, "api_type": null, "api_version": null, "organization_id": null}, "allOf": [{"$ref": "#/definitions/RetrievalSettings"}]}' required={false} default="{'n_retrieve': 50, 'n_final': 10, 'use_reranking': True, 'rerank_group_size': 5, 'ignore_files': [], 'openai_api_key': None, 'api_base': None, 'api_type': None, 'api_version': None, 'organization_id': None}"/>
|
||||
16
docs/docs/reference/config.mdx
Normal file
16
docs/docs/reference/config.mdx
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import Schema from "@site/static/schemas/config.json";
|
||||
import JSONSchemaViewer from "@theme/JSONSchemaViewer";
|
||||
|
||||
# Configuration Options
|
||||
|
||||
The following shows the JSON Schema definition for `config.json`:
|
||||
|
||||
<JSONSchemaViewer
|
||||
schema={Schema}
|
||||
resolverOptions={{
|
||||
jsonPointer:
|
||||
"#/definitions/continuedev__core__config__serialized_config__SerializedContinueConfig",
|
||||
}}
|
||||
/>
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json)
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
---
|
||||
title: Telemetry
|
||||
title: 🦔 Telemetry
|
||||
description: Continue collects anonymous usage information
|
||||
keywords: [telemetry, anonymous, usage info, opt out]
|
||||
---
|
||||
|
|
@ -8,16 +8,15 @@ keywords: [telemetry, anonymous, usage info, opt out]
|
|||
|
||||
## Overview
|
||||
|
||||
Continue collects and reports **anonymous** usage information. This data is essential to understanding how we should improve the library. You can opt out of it at any time. We use [Posthog](https://posthog.com/), an open source platform for product analytics, to collect and store the data. You can review the code [here](https://github.com/continuedev/continue/tree/main/server/continuedev/libs/util/telemetry.py).
|
||||
Continue collects and reports **anonymous** usage information. This data is essential to understanding how we should improve the product. You can opt out of it at any time. We use [Posthog](https://posthog.com/), an open source platform for product analytics, to collect and store the data. You can review the code [here](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx).
|
||||
|
||||
## What we track
|
||||
|
||||
We track
|
||||
|
||||
- the steps that are run and their parameters
|
||||
- whether you accept or reject suggestions (not the code itself)
|
||||
- the traceback when an error occurs
|
||||
- the name of your OS
|
||||
- the name of slash commands that are run
|
||||
- the name of your OS and IDE
|
||||
- the name of the default model you configured
|
||||
|
||||
All data is anonymous and cleaned of PII before being sent to PostHog.
|
||||
|
|
@ -33,4 +32,4 @@ The `~/.continue` directory contains a `config.json` file that looks like this:
|
|||
}
|
||||
```
|
||||
|
||||
You can turn off anonymous telemetry by changing the value of `allowAnonymousTelemetry` to `false`.
|
||||
You can turn off anonymous telemetry by changing the value of `allowAnonymousTelemetry` to `false`. Alternatively, you can uncheck the "Continue: Telemetry Enabled" box in VS Code settings.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
---
|
||||
title: Troubleshooting
|
||||
title: ❓ Troubleshooting
|
||||
description: Troubleshooting while waiting for help during beta / alpha testing
|
||||
keywords: [reload, delete, manually, logs, server, console]
|
||||
---
|
||||
|
|
@ -18,13 +18,17 @@ To solve many problems, the first step is reading the logs to find the relevant
|
|||
4. Select the `Console` tab
|
||||
5. Read the console logs
|
||||
|
||||
## Download a Newer Version (VS Code)
|
||||
## Download a Newer Version
|
||||
|
||||
If you are using an older version of the Continue extension, particularly one which depends on the separate Python server, we would recommend downloading the latest version of the extension, as we are constantly making bug fixes and are likely to have solved any major issues.
|
||||
|
||||
## Download an Older Version (VS Code)
|
||||
## Download an Older Version
|
||||
|
||||
If you've tried everything, reported an error, know that a previous version was working for you, and are waiting to hear back, you can try downloading an older version of the extension. All versions are hosted on the Open VSX Registry [here](https://open-vsx.org/extension/Continue/continue). Once you've downloaded the extension, which will be a .vsix file, you can install it manually by following the instructions [here](https://code.visualstudio.com/docs/editor/extension-gallery#_install-from-a-vsix).
|
||||
If you've tried everything, reported an error, know that a previous version was working for you, and are waiting to hear back, you can try downloading an older version of the extension.
|
||||
|
||||
For VS Code, All versions are hosted on the Open VSX Registry [here](https://open-vsx.org/extension/Continue/continue). Once you've downloaded the extension, which will be a .vsix file, you can install it manually by following the instructions [here](https://code.visualstudio.com/docs/editor/extension-gallery#_install-from-a-vsix).
|
||||
|
||||
You can find older versions of the JetBrains extension on their [marketplace](https://plugins.jetbrains.com/plugin/22707-continue), which will walk you through installing from disk.
|
||||
|
||||
## Still having trouble?
|
||||
|
||||
|
|
|
|||
|
|
@ -8,11 +8,19 @@ keywords: [talk, embeddings, codebase, experimental]
|
|||
|
||||
Continue indexes your codebase so that it can later automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally with `all-MiniLM-L6-v2` and stored locally in `~/.continue/index`.
|
||||
|
||||
## How to use codebase retrieval
|
||||
<!-- ## How to use codebase retrieval -->
|
||||
|
||||
Currently, the codebase retrieval feature is available as the "codebase" context provider. You can use it by typing `@codebase` in the input box, and then asking a question. The contents of the input box will be compared with the embeddings from the rest of the codebase to determine relevant files.
|
||||
Currently, the codebase retrieval feature is available as the "codebase" and "folder" context providers. You can use them by typing `@codebase` or `@folder` in the input box, and then asking a question. The contents of the input box will be compared with the embeddings from the rest of the codebase (or folder) to determine relevant files.
|
||||
|
||||
There are a few options that let you configure the behavior of the codebase context provider. These can be set in `config.json`:
|
||||
<!-- Here are some common use cases where it can be useful:
|
||||
|
||||
### Asking high-level codebase questions
|
||||
|
||||
- -->
|
||||
|
||||
## Configuration
|
||||
|
||||
There are a few options that let you configure the behavior of the codebase context provider. These can be set in `config.json`, and are the same for the codebase and folder context providers:
|
||||
|
||||
```json title="~/.continue/config.json"
|
||||
{
|
||||
|
|
@ -73,6 +81,8 @@ We also support other methods of generating embeddings, which can be configured
|
|||
|
||||
### OpenAI
|
||||
|
||||
OpenAI's [ada-002 embeddings](https://platform.openai.com/docs/guides/embeddings) are high dimensional embeddings that give great performance on both text and code.
|
||||
|
||||
```json title="~/.continue/config.json"
|
||||
{
|
||||
"embeddingsProvider": {
|
||||
|
|
|
|||
|
|
@ -16,29 +16,28 @@ If you need any help migrating, please reach out to us on Discord.
|
|||
|
||||
> Continue has moved to using Typescript configuration. To learn about this, please see [Configuration as Code](../customization/code-config.md).
|
||||
|
||||
For configuration that requires code, we now provide a simpler interface that works alongside config.json. In the same folder, `~/.continue`, create a file named `config.py` (the same name as before) and add a function called `modify_config`. This function should take a [`ContinueConfig`](https://github.com/continuedev/continue/blob/main/server/continuedev/core/config.py) object as its only argument, and return a `ContinueConfig` object. This object is essentially the same as the one that was previously defined in `config.py`. This allows you to modify the initial configuration object defined in your `config.json`. Here's an example that cuts the temperature in half:
|
||||
For configuration that requires code, we now provide a simpler interface that works alongside config.json. In the same folder, `~/.continue`, create a file named `config.ts` and add a function called `modifyConfig`. This function should take a `Config` object as its only argument, and return a `Config` object. This object is essentially the same as the one that was previously defined in `config.py`. This allows you to modify the initial configuration object defined in your `config.json`. Here's an example that cuts the temperature in half:
|
||||
|
||||
```python
|
||||
from continuedev.core.config import ContinueConfig
|
||||
|
||||
def modify_config(config: ContinueConfig) -> ContinueConfig:
|
||||
config.completion_options.temperature /= 2
|
||||
return config
|
||||
```typescript
|
||||
function modifyConfig(config: Config): Config {
|
||||
config.completionOptions.temperature /= 2;
|
||||
return config;
|
||||
}
|
||||
```
|
||||
|
||||
To summarize, these are the steps taken to load your configuration:
|
||||
|
||||
1. Load `~/.continue/config.json`
|
||||
2. Convert this into a `ContinueConfig` object
|
||||
3. If `~/.continue/config.py` exists and has defined `modify_config` correctly, call `modify_config` with the `ContinueConfig` object to generate the final configuration
|
||||
2. Convert this into a `Config` object
|
||||
3. If `~/.continue/config.ts` exists and has defined `modifyConfig` correctly, call `modifyConfig` with the `Config` object to generate the final configuration
|
||||
|
||||
## List of Changes
|
||||
|
||||
### `completion_options`
|
||||
### `completionOptions`
|
||||
|
||||
The properties `top_p`, `top_k`, `temperature`, `presence_penalty`, and `frequency_penalty` have been moved into a single object called `completion_options`. It can be specified at the top level of the config or within a `models` object.
|
||||
The properties `topP`, `topK`, `temperature`, `presencePenalty`, and `frequencyPenalty` have been moved into a single object called `completionOptions`. It can be specified at the top level of the config or within a `models` object.
|
||||
|
||||
### `request_options`
|
||||
### `requestOptions`
|
||||
|
||||
The properties `timeout`, `verify_ssl`, `ca_bundle_path`, `proxy`, and `headers` have been moved into a single object called `request_options`, which can be specified for each `models` object.
|
||||
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ keywords: [no internet, air-gapped, local model]
|
|||
|
||||
# Running Continue without Internet
|
||||
|
||||
Continue can be run even on an air-gapped computer if you use a local model. You'll have to make a few adjustments for this to work.
|
||||
Continue can be run even on an air-gapped computer if you use a local model. Only a few adjustments are required for this to work.
|
||||
|
||||
1. Download the latest .vsix file from the [Open VSX Registry](https://open-vsx.org/extension/Continue/continue) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix).
|
||||
2. Open `~/.continue/config.json` and set `"allowAnonymousTelemetry": false`. This will stop Continue from attempting requests to PostHog.
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
// @ts-check
|
||||
// Note: type annotations allow type checking and IDEs autocompletion
|
||||
|
||||
const lightCodeTheme = require("prism-react-renderer/themes/github");
|
||||
const darkCodeTheme = require("prism-react-renderer/themes/dracula");
|
||||
const { themes } = require("prism-react-renderer");
|
||||
const lightCodeTheme = themes.github;
|
||||
const darkCodeTheme = themes.dracula;
|
||||
|
||||
/** @type {import('@docusaurus/types').Config} */
|
||||
const config = {
|
||||
|
|
@ -33,6 +34,8 @@ const config = {
|
|||
locales: ["en"],
|
||||
},
|
||||
|
||||
themes: [["docusaurus-json-schema-plugin", {}]],
|
||||
|
||||
presets: [
|
||||
[
|
||||
"classic",
|
||||
|
|
@ -56,7 +59,13 @@ const config = {
|
|||
themeConfig:
|
||||
/** @type {import('@docusaurus/preset-classic').ThemeConfig} */
|
||||
({
|
||||
metadata: [{name: 'keywords', content: 'open source, ai, vscode, intellij, jetbrains, developer tools, chatgpt, copilot, llm'}],
|
||||
metadata: [
|
||||
{
|
||||
name: "keywords",
|
||||
content:
|
||||
"open source, ai, vscode, intellij, jetbrains, developer tools, chatgpt, copilot, llm",
|
||||
},
|
||||
],
|
||||
// Replace with your project's social card
|
||||
image: "img/continue-social-card.png",
|
||||
navbar: {
|
||||
|
|
@ -128,6 +137,7 @@ const config = {
|
|||
prism: {
|
||||
theme: lightCodeTheme,
|
||||
darkTheme: darkCodeTheme,
|
||||
additionalLanguages: ["json"],
|
||||
},
|
||||
algolia: {
|
||||
// The application ID provided by Algolia
|
||||
|
|
|
|||
17120
docs/package-lock.json
generated
17120
docs/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -15,17 +15,18 @@
|
|||
"write-heading-ids": "docusaurus write-heading-ids"
|
||||
},
|
||||
"dependencies": {
|
||||
"@docusaurus/core": "2.4.0",
|
||||
"@docusaurus/plugin-client-redirects": "2.4.0",
|
||||
"@docusaurus/preset-classic": "2.4.0",
|
||||
"@mdx-js/react": "^1.6.22",
|
||||
"clsx": "^1.2.1",
|
||||
"prism-react-renderer": "^1.3.5",
|
||||
"react": "^17.0.2",
|
||||
"react-dom": "^17.0.2"
|
||||
"@docusaurus/core": "3.1.0",
|
||||
"@docusaurus/plugin-client-redirects": "3.1.0",
|
||||
"@docusaurus/preset-classic": "3.1.0",
|
||||
"@mdx-js/react": "^3.0.0",
|
||||
"clsx": "^2.1.0",
|
||||
"docusaurus-json-schema-plugin": "^1.11.0",
|
||||
"prism-react-renderer": "^2.3.1",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@docusaurus/module-type-aliases": "2.4.0"
|
||||
"@docusaurus/module-type-aliases": "3.1.0"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
|
|
|
|||
|
|
@ -38,7 +38,6 @@ const sidebars = {
|
|||
"customization/overview",
|
||||
"customization/context-providers",
|
||||
"customization/slash-commands",
|
||||
"customization/other-configuration",
|
||||
],
|
||||
},
|
||||
{
|
||||
|
|
@ -47,10 +46,10 @@ const sidebars = {
|
|||
collapsible: true,
|
||||
collapsed: true,
|
||||
items: [
|
||||
"walkthroughs/codellama",
|
||||
// "walkthroughs/codellama",
|
||||
"walkthroughs/running-continue-without-internet",
|
||||
"walkthroughs/codebase-embeddings",
|
||||
"walkthroughs/config-file-migration",
|
||||
// "walkthroughs/config-file-migration",
|
||||
],
|
||||
},
|
||||
"development-data",
|
||||
|
|
|
|||
BIN
docs/static/img/context-provider-example.png
vendored
BIN
docs/static/img/context-provider-example.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 131 KiB After Width: | Height: | Size: 60 KiB |
BIN
docs/static/img/jetbrains-quickstart.png
vendored
Normal file
BIN
docs/static/img/jetbrains-quickstart.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 371 KiB |
BIN
docs/static/img/move-to-right-sidebar.png
vendored
Normal file
BIN
docs/static/img/move-to-right-sidebar.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 762 KiB |
BIN
docs/static/img/slash-commands.png
vendored
Normal file
BIN
docs/static/img/slash-commands.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 93 KiB |
1219
docs/static/schemas/config.json
vendored
Normal file
1219
docs/static/schemas/config.json
vendored
Normal file
File diff suppressed because it is too large
Load diff
2
extensions/vscode/.gitignore
vendored
2
extensions/vscode/.gitignore
vendored
|
|
@ -8,6 +8,4 @@ src/client
|
|||
|
||||
gui
|
||||
exe
|
||||
|
||||
sync.node
|
||||
bin
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
{
|
||||
"title": "SerializedContinueConfig",
|
||||
"title": "config.json",
|
||||
"$ref": "#/definitions/continuedev__core__config__serialized_config__SerializedContinueConfig",
|
||||
"definitions": {
|
||||
"BaseCompletionOptions": {
|
||||
|
|
@ -1139,7 +1139,7 @@
|
|||
"required": ["name"]
|
||||
},
|
||||
"continuedev__core__config__serialized_config__SerializedContinueConfig": {
|
||||
"title": "SerializedContinueConfig",
|
||||
"title": "config.json",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"allowAnonymousTelemetry": {
|
||||
|
|
|
|||
|
|
@ -13,6 +13,12 @@ if (args[2] === "--target") {
|
|||
(async () => {
|
||||
console.log("Packaging extension for target ", target);
|
||||
|
||||
// Copy config_schema.json to config.json in docs
|
||||
fs.copyFileSync(
|
||||
"config_schema.json",
|
||||
path.join("..", "..", "docs", "static", "schemas", "config.json")
|
||||
);
|
||||
|
||||
if (!process.cwd().endsWith("vscode")) {
|
||||
// This is sometimes run from root dir instead (e.g. in VS Code tasks)
|
||||
process.chdir("extensions/vscode");
|
||||
|
|
@ -84,10 +90,40 @@ if (args[2] === "--target") {
|
|||
}
|
||||
|
||||
// Copy over native / wasm modules //
|
||||
if (!ghAction()) {
|
||||
if (!ghAction() && fs.existsSync("../bin")) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If target doesn't exist, but the bin folder also doesn't, we want to download it once, to help set up the dev environment
|
||||
if (!target) {
|
||||
const os = {
|
||||
aix: "linux",
|
||||
darwin: "darwin",
|
||||
freebsd: "linux",
|
||||
linux: "linux",
|
||||
openbsd: "linux",
|
||||
sunos: "linux",
|
||||
win32: "win32",
|
||||
}[process.platform];
|
||||
const arch = {
|
||||
arm: "arm64",
|
||||
arm64: "arm64",
|
||||
ia32: "x64",
|
||||
loong64: "arm64",
|
||||
mips: "arm64",
|
||||
mipsel: "arm64",
|
||||
ppc: "x64",
|
||||
ppc64: "x64",
|
||||
riscv64: "arm64",
|
||||
s390: "x64",
|
||||
s390x: "x64",
|
||||
x64: "x64",
|
||||
}[process.arch];
|
||||
|
||||
target = `${os}-${arch}`;
|
||||
console.log("Detected target: ", target);
|
||||
}
|
||||
|
||||
process.chdir("../extensions/vscode");
|
||||
|
||||
// onnxruntime-node
|
||||
|
|
|
|||
|
|
@ -465,7 +465,9 @@ async function loadFullConfigNode(ide: IDE): Promise<ContinueConfig> {
|
|||
if (configJsContents) {
|
||||
try {
|
||||
// Try config.ts first
|
||||
const module = await require(getConfigJsPath(true));
|
||||
const configJsPath = getConfigJsPath(true);
|
||||
const module = await require(configJsPath);
|
||||
delete require.cache[require.resolve(configJsPath)];
|
||||
if (!module.modifyConfig) {
|
||||
throw new Error("config.ts does not export a modifyConfig function.");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
// Make sure odd-numbered version isn't published to main release. This will irreversibly cause us to bump the minor version by 2
|
||||
import * as fs from "fs";
|
||||
const fs = require("fs");
|
||||
|
||||
const packageJson = fs.readFileSync("package.json");
|
||||
const packageJsonJson = JSON.parse(packageJson);
|
||||
|
|
|
|||
|
|
@ -211,6 +211,12 @@ function useChatHandler(dispatch: Dispatch) {
|
|||
await _streamNormalInput(messages);
|
||||
} else {
|
||||
const [slashCommand, commandInput] = commandAndInput;
|
||||
posthog.capture("step run", {
|
||||
step_name: slashCommand.name,
|
||||
params: {
|
||||
user_input: commandInput,
|
||||
},
|
||||
});
|
||||
await _streamSlashCommand(messages, slashCommand, commandInput);
|
||||
}
|
||||
} catch (e) {
|
||||
|
|
|
|||
|
|
@ -22,4 +22,5 @@ pushd extensions/vscode
|
|||
# This does way too many things inline but is the common denominator between many of the scripts
|
||||
npm install
|
||||
npm link core
|
||||
npm run prepackage
|
||||
npm run package
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
# Changelog
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
|
||||
and is generated by [Changie](https://github.com/miniscruff/changie).
|
||||
|
||||
|
||||
## v0.1.104 - 2023-12-25
|
||||
|
||||
### Added
|
||||
|
||||
- Continuous and faster syncing of codebase index
|
||||
|
||||
### Removed
|
||||
|
||||
- No longer using Continue Python server
|
||||
|
||||
## v0.1.99 - 2023-11-19
|
||||
|
||||
### Changed
|
||||
|
||||
- migrated to .json config file format
|
||||
655
sync/src/sync.rs
Normal file
655
sync/src/sync.rs
Normal file
|
|
@ -0,0 +1,655 @@
|
|||
mod merkle;
|
||||
use homedir::get_my_home;
|
||||
use merkle::{compute_tree_for_dir, diff, hash_string};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::{self, File, OpenOptions},
|
||||
io::{Read, Seek, SeekFrom, Write},
|
||||
path::{Path, PathBuf},
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use self::merkle::{ObjDescription, Tree};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Tag<'a> {
|
||||
pub dir: &'a Path,
|
||||
pub branch: &'a str,
|
||||
pub provider_id: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> Tag<'a> {
|
||||
pub fn to_string(&self) -> String {
|
||||
return format!(
|
||||
"{}::{}::{}",
|
||||
self.dir.to_str().unwrap(),
|
||||
self.branch,
|
||||
self.provider_id
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_seps_from_path(dir: &Path) -> String {
|
||||
let mut path = String::new();
|
||||
for component in dir.components() {
|
||||
path.push_str(component.as_os_str().to_str().unwrap());
|
||||
}
|
||||
|
||||
// Remove leading slash
|
||||
if path.starts_with('/') || path.starts_with('\\') {
|
||||
path.remove(0);
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
fn path_for_tag(tag: &Tag) -> PathBuf {
|
||||
let mut path = get_my_home().unwrap().unwrap();
|
||||
path.push(".continue/index/tags");
|
||||
<<<<<<<< HEAD:sync/src/sync.rs
|
||||
path.push(remove_seps_from_path(dir));
|
||||
if let Some(branch) = branch {
|
||||
path.push(branch);
|
||||
} else {
|
||||
path.push("main");
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
// /// Stored in ~/.continue/index/.last_sync
|
||||
// fn get_last_sync_time(dir: &Path, branch: Option<&str>) -> u64 {
|
||||
// // TODO: Error handle here
|
||||
// let path = path_for_tag(dir, branch).join(".last_sync");
|
||||
========
|
||||
path.push(remove_seps_from_path(tag.dir));
|
||||
path.push(tag.branch);
|
||||
path.push(tag.provider_id);
|
||||
return path;
|
||||
}
|
||||
|
||||
/// Stored in ~/.continue/index/.last_sync
|
||||
fn get_last_sync_time(tag: &Tag) -> u64 {
|
||||
// TODO: Error handle here
|
||||
let path = path_for_tag(tag).join(".last_sync");
|
||||
>>>>>>>> preview:sync/src/sync/mod.rs
|
||||
|
||||
// let mut file = File::open(path).unwrap();
|
||||
// let mut contents = String::new();
|
||||
// file.read_to_string(&mut contents).unwrap();
|
||||
|
||||
// contents.parse::<u64>().unwrap()
|
||||
// }
|
||||
|
||||
fn write_sync_time(tag: &Tag) {
|
||||
let path = path_for_tag(tag).join(".last_sync");
|
||||
|
||||
let mut file = File::create(path).unwrap();
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
file.write_all(now.to_string().as_bytes()).unwrap();
|
||||
}
|
||||
|
||||
<<<<<<<< HEAD:sync/src/sync.rs
|
||||
// /// Use stat to find files since last sync time
|
||||
// pub fn get_modified_files(dir: &Path, branch: Option<&str>) -> Vec<PathBuf> {
|
||||
// let last_sync_time = get_last_sync_time(dir, branch);
|
||||
========
|
||||
/// Use stat to find files since last sync time
|
||||
pub fn get_modified_files(tag: &Tag) -> Vec<PathBuf> {
|
||||
let last_sync_time = get_last_sync_time(tag);
|
||||
let mut modified_files = Vec::new();
|
||||
for entry in build_walk(tag.dir) {
|
||||
let entry = entry.unwrap();
|
||||
let path = entry.path();
|
||||
let metadata = path.metadata().unwrap();
|
||||
let modified = metadata.modified().unwrap();
|
||||
>>>>>>>> preview:sync/src/sync/mod.rs
|
||||
|
||||
// build_walk(dir)
|
||||
// .filter_map(|entry| {
|
||||
// let entry = entry.unwrap();
|
||||
// let path = entry.path();
|
||||
// let metadata = path.metadata().unwrap();
|
||||
// let modified = metadata.modified().unwrap();
|
||||
|
||||
// if modified.duration_since(UNIX_EPOCH).unwrap().as_secs() > last_sync_time {
|
||||
// Some(path.to_path_buf())
|
||||
// } else {
|
||||
// None
|
||||
// }
|
||||
// })
|
||||
// .collect()
|
||||
// }
|
||||
|
||||
// Merkle trees are unique to directories, even if nested, but .index_cache is shared between all
|
||||
|
||||
struct DiskSet {
|
||||
file: File,
|
||||
}
|
||||
|
||||
const ITEM_SIZE: usize = 20;
|
||||
|
||||
impl DiskSet {
|
||||
pub fn new(path: &str) -> Self {
|
||||
let path = Path::new(path);
|
||||
if !path.exists() {
|
||||
File::create(path).unwrap();
|
||||
}
|
||||
|
||||
Self {
|
||||
file: OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(path)
|
||||
.unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn contains(&mut self, item: &[u8; ITEM_SIZE]) -> bool {
|
||||
self.file.seek(SeekFrom::Start(0)).unwrap();
|
||||
let mut buffer = [0; ITEM_SIZE];
|
||||
while self.file.read_exact(&mut buffer).is_ok() {
|
||||
if &buffer == item {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn add(&mut self, item: &[u8; ITEM_SIZE]) {
|
||||
if self.contains(item) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.file.write_all(item).unwrap();
|
||||
self.file.flush().unwrap();
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, item: &[u8; ITEM_SIZE]) {
|
||||
self.file.seek(SeekFrom::Start(0)).unwrap();
|
||||
let mut buffer = [0; ITEM_SIZE];
|
||||
let mut pos = 0;
|
||||
let mut found = false;
|
||||
while self.file.read_exact(&mut buffer).is_ok() {
|
||||
if &buffer == item {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
pos = self.file.stream_position().unwrap() as usize;
|
||||
}
|
||||
|
||||
if found {
|
||||
// Calculate the position of the last item
|
||||
let len = self.file.metadata().unwrap().len() as usize;
|
||||
let last_item_pos = len - ITEM_SIZE;
|
||||
|
||||
// Move the last item in the file to the position of the item we want to remove
|
||||
self.file
|
||||
.seek(SeekFrom::Start(last_item_pos as u64))
|
||||
.unwrap();
|
||||
self.file.read_exact(&mut buffer).unwrap();
|
||||
self.file.seek(SeekFrom::Start(pos as u64)).unwrap();
|
||||
self.file.write_all(&buffer).unwrap();
|
||||
|
||||
// Truncate the file at the position of the last item
|
||||
self.file.set_len(last_item_pos as u64).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct IndexCache<'a> {
|
||||
tag: Box<Tag<'a>>,
|
||||
global_cache: DiskSet,
|
||||
tag_cache: DiskSet,
|
||||
}
|
||||
|
||||
impl<'a> IndexCache<'a> {
|
||||
fn index_cache_path_for_tag(tag: &Tag) -> PathBuf {
|
||||
let mut path = path_for_tag(tag);
|
||||
path.push(".index_cache");
|
||||
path
|
||||
}
|
||||
|
||||
fn rev_tags_dir(provider_id: &str) -> PathBuf {
|
||||
let mut path = IndexCache::provider_dir(provider_id);
|
||||
path.push("rev_tags");
|
||||
return path;
|
||||
}
|
||||
|
||||
fn rev_tags_path(hash: [u8; ITEM_SIZE], provider_id: &str) -> PathBuf {
|
||||
let hash_str = hash_string(hash);
|
||||
let mut path = IndexCache::rev_tags_dir(provider_id);
|
||||
// Branch by 1) first two chars of hash
|
||||
path.push(&hash_str[0..2]);
|
||||
path
|
||||
}
|
||||
|
||||
fn tag_str(&self) -> String {
|
||||
<<<<<<<< HEAD:sync/src/sync.rs
|
||||
format!("{}::{}", self.dir.to_str().unwrap(), self.branch)
|
||||
}
|
||||
|
||||
fn new(dir: &Path, branch: Option<&str>) -> Self {
|
||||
Self {
|
||||
dir: Box::from(dir),
|
||||
branch: Box::from(branch.unwrap_or("main")),
|
||||
global_cache: DiskSet::new(
|
||||
get_my_home()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.join(".continue/index/.index_cache")
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
),
|
||||
tag_cache: DiskSet::new(
|
||||
Self::index_cache_path_for_tag(dir, branch.unwrap_or("main"))
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
),
|
||||
}
|
||||
========
|
||||
return self.tag.to_string();
|
||||
}
|
||||
|
||||
fn provider_dir(provider_id: &str) -> PathBuf {
|
||||
let mut path = get_my_home().unwrap().unwrap();
|
||||
path.push(".continue/index/providers");
|
||||
path.push(provider_id);
|
||||
return path;
|
||||
}
|
||||
|
||||
fn new(tag: &'a Tag) -> IndexCache<'a> {
|
||||
return IndexCache {
|
||||
tag: Box::new(tag.clone()),
|
||||
global_cache: DiskSet::new(
|
||||
IndexCache::provider_dir(tag.provider_id)
|
||||
.join(".index_cache")
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
),
|
||||
tag_cache: DiskSet::new(IndexCache::index_cache_path_for_tag(tag).to_str().unwrap()),
|
||||
};
|
||||
>>>>>>>> preview:sync/src/sync/mod.rs
|
||||
}
|
||||
|
||||
// rev_tags files are just json files with the following format:
|
||||
// { "hash": ["tag1", "tag2", ...], ... }
|
||||
|
||||
// TODO: You could add_bulk, remove_bulk if this gets slow
|
||||
|
||||
<<<<<<<< HEAD:sync/src/sync.rs
|
||||
fn read_rev_tags(hash: [u8; ITEM_SIZE]) -> HashMap<String, Vec<String>> {
|
||||
let rev_tags_path = Self::rev_tags_path(hash);
|
||||
========
|
||||
fn read_rev_tags(&self, hash: [u8; ITEM_SIZE]) -> HashMap<String, Vec<String>> {
|
||||
let rev_tags_path = IndexCache::rev_tags_path(hash, self.tag.provider_id);
|
||||
>>>>>>>> preview:sync/src/sync/mod.rs
|
||||
let mut rev_tags_file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.open(rev_tags_path)
|
||||
.unwrap();
|
||||
let mut contents = String::new();
|
||||
rev_tags_file.read_to_string(&mut contents).unwrap();
|
||||
|
||||
serde_json::from_str(&contents).unwrap_or_default()
|
||||
}
|
||||
|
||||
<<<<<<<< HEAD:sync/src/sync.rs
|
||||
fn write_rev_tags(hash: [u8; ITEM_SIZE], rev_tags: &HashMap<String, Vec<String>>) {
|
||||
let rev_tags_path = Self::rev_tags_path(hash);
|
||||
========
|
||||
fn write_rev_tags(&self, hash: [u8; ITEM_SIZE], rev_tags: HashMap<String, Vec<String>>) {
|
||||
let rev_tags_path = IndexCache::rev_tags_path(hash, self.tag.provider_id);
|
||||
>>>>>>>> preview:sync/src/sync/mod.rs
|
||||
let mut rev_tags_file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.open(rev_tags_path)
|
||||
.unwrap();
|
||||
let json = serde_json::to_string(&rev_tags).unwrap();
|
||||
|
||||
// Rewrite the whole file
|
||||
rev_tags_file.set_len(0).unwrap();
|
||||
rev_tags_file.seek(SeekFrom::Start(0)).unwrap();
|
||||
rev_tags_file.write_all(json.as_bytes()).unwrap();
|
||||
rev_tags_file.flush().unwrap();
|
||||
}
|
||||
|
||||
fn add_global(&mut self, item: &ObjDescription) {
|
||||
self.global_cache.add(&item.hash);
|
||||
self.tag_cache.add(&item.hash);
|
||||
|
||||
// Add to rev_tags
|
||||
let mut rev_tags = Self::read_rev_tags(item.hash);
|
||||
let tag_str = self.tag_str();
|
||||
let hash_str = hash_string(item.hash);
|
||||
if !rev_tags.contains_key(hash_str.as_str()) {
|
||||
rev_tags.insert(hash_str.clone(), Vec::new());
|
||||
}
|
||||
rev_tags.get_mut(hash_str.as_str()).unwrap().push(tag_str);
|
||||
Self::write_rev_tags(item.hash, &rev_tags);
|
||||
}
|
||||
|
||||
fn global_remove(&mut self, item: &ObjDescription) {
|
||||
self.global_cache.remove(&item.hash);
|
||||
self.tag_cache.remove(&item.hash);
|
||||
|
||||
// Remove from rev_tags
|
||||
let mut rev_tags = Self::read_rev_tags(item.hash);
|
||||
let hash_str = hash_string(item.hash);
|
||||
if rev_tags.contains_key(hash_str.as_str()) {
|
||||
rev_tags.remove(hash_str.as_str());
|
||||
}
|
||||
Self::write_rev_tags(item.hash, &rev_tags);
|
||||
}
|
||||
|
||||
fn local_remove(&mut self, item: &ObjDescription) {
|
||||
self.tag_cache.remove(&item.hash);
|
||||
|
||||
// Remove from rev_tags
|
||||
let mut rev_tags = Self::read_rev_tags(item.hash);
|
||||
let tag_str = self.tag_str();
|
||||
let hash_str = hash_string(item.hash);
|
||||
if rev_tags.contains_key(hash_str.as_str()) {
|
||||
let tags = rev_tags.get_mut(hash_str.as_str()).unwrap();
|
||||
let index = tags.iter().position(|x| *x == tag_str).unwrap();
|
||||
tags.remove(index);
|
||||
if tags.is_empty() {
|
||||
rev_tags.remove(hash_str.as_str());
|
||||
}
|
||||
}
|
||||
Self::write_rev_tags(item.hash, &rev_tags);
|
||||
}
|
||||
|
||||
fn global_contains(&mut self, hash: &[u8; ITEM_SIZE]) -> bool {
|
||||
self.global_cache.contains(hash)
|
||||
}
|
||||
|
||||
// fn tag_contains(&mut self, hash: &[u8; ITEM_SIZE]) -> bool {
|
||||
// self.tag_cache.contains(hash)
|
||||
// }
|
||||
|
||||
fn get_rev_tags(hash: &[u8; ITEM_SIZE]) -> Vec<String> {
|
||||
let mut rev_tags = Self::read_rev_tags(*hash);
|
||||
let hash_str = hash_string(*hash);
|
||||
if rev_tags.contains_key(hash_str.as_str()) {
|
||||
rev_tags.remove(hash_str.as_str()).unwrap()
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sync(
|
||||
tag: &Tag,
|
||||
) -> Result<
|
||||
(
|
||||
Vec<(String, String)>,
|
||||
Vec<(String, String)>,
|
||||
Vec<(String, String)>,
|
||||
Vec<(String, String)>,
|
||||
),
|
||||
Box<dyn std::error::Error>,
|
||||
> {
|
||||
// Make sure that the tag directory exists
|
||||
// Create the directory and all its parent directories if they don't exist
|
||||
fs::create_dir_all(path_for_tag(tag)).unwrap();
|
||||
if let Some(parent) = IndexCache::rev_tags_path([0; ITEM_SIZE], tag.provider_id).parent() {
|
||||
fs::create_dir_all(parent).unwrap();
|
||||
}
|
||||
|
||||
let mut tree_path = path_for_tag(tag);
|
||||
tree_path.push("merkle_tree");
|
||||
|
||||
let old_tree = Tree::load(&tree_path).unwrap_or_default();
|
||||
|
||||
// Calculate and save new tree
|
||||
// TODO: Use modified files to speed up calculation
|
||||
// let modified_files = get_modified_files(dir, branch);
|
||||
let new_tree = compute_tree_for_dir(tag.dir, None)?;
|
||||
|
||||
// Update last sync time
|
||||
write_sync_time(tag);
|
||||
|
||||
// Save new tree
|
||||
new_tree.persist(&tree_path);
|
||||
|
||||
// Compute diff
|
||||
let (add, remove) = diff(&old_tree, &new_tree);
|
||||
|
||||
// Compute the four action types: compute, remove, add tag, remove tag,
|
||||
// transform into desired format: [(path, hash), ...],
|
||||
// and update .index_cache
|
||||
let mut index_cache = IndexCache::new(tag);
|
||||
|
||||
let mut compute: Vec<(String, String)> = Vec::new();
|
||||
let mut delete: Vec<(String, String)> = Vec::new();
|
||||
let mut add_label: Vec<(String, String)> = Vec::new();
|
||||
let mut remove_label: Vec<(String, String)> = Vec::new();
|
||||
|
||||
for item in add {
|
||||
if !item.is_blob {
|
||||
continue;
|
||||
}
|
||||
let path = item.path.as_str().to_string();
|
||||
let hash = hash_string(item.hash);
|
||||
|
||||
// Need to specify between global and local contains
|
||||
if index_cache.global_contains(&item.hash) {
|
||||
add_label.push((path, hash));
|
||||
|
||||
// Add to local cache
|
||||
index_cache.add_global(&item);
|
||||
} else {
|
||||
compute.push((path, hash));
|
||||
|
||||
// Add to global and local cache
|
||||
index_cache.add_global(&item);
|
||||
}
|
||||
}
|
||||
|
||||
for item in remove {
|
||||
if !item.is_blob {
|
||||
continue;
|
||||
}
|
||||
if index_cache.global_contains(&item.hash) {
|
||||
if IndexCache::get_rev_tags(&item.hash).len() <= 1 {
|
||||
// If it's cached only for this tag, remove it from the global cache as well
|
||||
index_cache.global_remove(&item);
|
||||
let hash = hash_string(item.hash);
|
||||
let path = item.path.as_str().to_string();
|
||||
delete.push((path, hash));
|
||||
} else {
|
||||
// Otherwise, remove label, remove from local cache
|
||||
index_cache.local_remove(&item);
|
||||
let hash = hash_string(item.hash);
|
||||
let path = item.path.as_str().to_string();
|
||||
remove_label.push((path, hash));
|
||||
}
|
||||
} else {
|
||||
// Should never happen
|
||||
}
|
||||
}
|
||||
|
||||
Ok((compute, delete, add_label, remove_label))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{sync::merkle::ObjectHash, utils::TempDirBuilder};
|
||||
use std::fs::remove_file;
|
||||
|
||||
#[test]
|
||||
fn test_disk_set() {
|
||||
let path = "testfile";
|
||||
let mut disk_set = DiskSet::new(path);
|
||||
|
||||
let item1: ObjectHash = [1; ITEM_SIZE];
|
||||
let item2: ObjectHash = [20; ITEM_SIZE];
|
||||
let item3: ObjectHash = [30; ITEM_SIZE];
|
||||
|
||||
// Test add and contains
|
||||
disk_set.add(&item1);
|
||||
disk_set.add(&item2);
|
||||
assert!(disk_set.contains(&item1));
|
||||
assert!(disk_set.contains(&item2));
|
||||
|
||||
// Test the exact contents of the file
|
||||
disk_set.file.seek(SeekFrom::Start(0)).unwrap();
|
||||
let mut buffer = [0; ITEM_SIZE];
|
||||
disk_set.file.read_exact(&mut buffer).unwrap();
|
||||
assert_eq!(buffer, item1);
|
||||
disk_set.file.read_exact(&mut buffer).unwrap();
|
||||
assert_eq!(buffer, item2);
|
||||
|
||||
// Test remove
|
||||
disk_set.remove(&item1);
|
||||
assert!(!disk_set.contains(&item1));
|
||||
assert!(disk_set.contains(&item2));
|
||||
|
||||
// Test one more add
|
||||
disk_set.add(&item3);
|
||||
assert!(disk_set.contains(&item3));
|
||||
|
||||
// Test the length of the file
|
||||
disk_set.file.seek(SeekFrom::Start(0)).unwrap();
|
||||
let mut buffer = [0; ITEM_SIZE];
|
||||
let mut count = 0;
|
||||
while disk_set.file.read_exact(&mut buffer).is_ok() {
|
||||
count += 1;
|
||||
}
|
||||
assert_eq!(count, 2);
|
||||
|
||||
// Clean up
|
||||
remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sync() {
|
||||
let ti = std::time::Instant::now();
|
||||
<<<<<<<< HEAD:sync/src/sync.rs
|
||||
let _results = sync(
|
||||
Path::new("/Users/natesesti/Desktop/continue"),
|
||||
Some("nate/pyO3"),
|
||||
);
|
||||
========
|
||||
let tag = Tag {
|
||||
dir: Path::new("../"),
|
||||
branch: "nate/pyO3",
|
||||
provider_id: "default",
|
||||
};
|
||||
let results = sync(&tag);
|
||||
>>>>>>>> preview:sync/src/sync/mod.rs
|
||||
println!("Sync took {:?}", ti.elapsed());
|
||||
// Vast majority (90+%) of this time is spent in compute_tree_for_dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_on_vscode_extension() {
|
||||
<<<<<<<< HEAD:sync/src/sync.rs
|
||||
let _results = sync(
|
||||
Path::new("/Users/natesesti/Desktop/continue/extensions/vscode"),
|
||||
Some("nate/pyO3"),
|
||||
);
|
||||
========
|
||||
let results = sync(&Tag {
|
||||
dir: Path::new("../extensions/vscode"),
|
||||
branch: "nate/pyO3",
|
||||
provider_id: "default",
|
||||
});
|
||||
>>>>>>>> preview:sync/src/sync/mod.rs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_double_sync() {
|
||||
let ti = std::time::Instant::now();
|
||||
let results = sync(&Tag {
|
||||
dir: Path::new("../"),
|
||||
branch: "nate/pyO3",
|
||||
provider_id: "default",
|
||||
})
|
||||
.expect("Sync failed.");
|
||||
println!("First sync took {:?}", ti.elapsed());
|
||||
assert!(!results.0.is_empty());
|
||||
assert!(!results.1.is_empty());
|
||||
|
||||
let ti = std::time::Instant::now();
|
||||
let results = sync(&Tag {
|
||||
dir: Path::new("../"),
|
||||
branch: "nate/pyO3",
|
||||
provider_id: "default",
|
||||
})
|
||||
.expect("Sync failed");
|
||||
println!("Second sync took {:?}", ti.elapsed());
|
||||
assert_eq!(results.0.len(), 0);
|
||||
assert_eq!(results.1.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sync_v3() {
|
||||
// Create temp directory
|
||||
let temp_dir = TempDirBuilder::new()
|
||||
.add("dir1/file1.txt", "File 1")
|
||||
.add("dir1/file2.txt", "File 2")
|
||||
.add("dir2/file3.txt", "File 3")
|
||||
.add("dir2/subdir/continue.py", "[continue for i in range(10)]")
|
||||
.add("__init__.py", "a = 5")
|
||||
.create();
|
||||
|
||||
let tag = &Tag {
|
||||
dir: temp_dir.path(),
|
||||
branch: "BRANCH",
|
||||
provider_id: "default",
|
||||
};
|
||||
// Sync once
|
||||
sync(&tag).expect("Sync failed.");
|
||||
|
||||
// Make changes
|
||||
let mut file = File::create(temp_dir.path().join("dir1/file1.txt")).unwrap();
|
||||
file.write_all(b"File 1 changed").unwrap();
|
||||
let mut file = File::create(temp_dir.path().join("dir2/file3.txt")).unwrap();
|
||||
file.write_all(b"File 3 changed").unwrap();
|
||||
|
||||
// Sync again
|
||||
let results = sync(tag).expect("Sync failed.");
|
||||
|
||||
// Check results
|
||||
assert_eq!(results.0.len(), 2);
|
||||
assert_eq!(results.1.len(), 2);
|
||||
assert_eq!(results.2.len(), 0);
|
||||
assert_eq!(results.3.len(), 0);
|
||||
|
||||
// Start a new branch
|
||||
|
||||
let tag2 = &Tag {
|
||||
dir: temp_dir.path(),
|
||||
branch: "BRANCH2",
|
||||
provider_id: "default",
|
||||
};
|
||||
// Sync again
|
||||
let results = sync(tag2).expect("Sync failed.");
|
||||
|
||||
// Check results
|
||||
assert_eq!(results.0.len(), 0);
|
||||
assert_eq!(results.1.len(), 0);
|
||||
assert_eq!(results.2.len(), 5);
|
||||
assert_eq!(results.3.len(), 0);
|
||||
|
||||
// Delete a file in this new branch
|
||||
remove_file(temp_dir.path().join("dir1/file2.txt")).unwrap();
|
||||
|
||||
// Sync again
|
||||
let results = sync(tag2).expect("Sync failed.");
|
||||
|
||||
// Check results
|
||||
assert_eq!(results.0.len(), 0);
|
||||
assert_eq!(results.1.len(), 0);
|
||||
assert_eq!(results.2.len(), 0);
|
||||
assert_eq!(results.3.len(), 1);
|
||||
}
|
||||
}
|
||||
|
|
@ -3,21 +3,20 @@ use ignore::{Walk, WalkBuilder};
|
|||
use serde::{Deserialize, Serialize};
|
||||
use sha1::{Digest, Sha1};
|
||||
use std::{
|
||||
io::{self, Read, Result, Write},
|
||||
io::{Read, Result, Write},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
pub type ObjectHash = [u8; 20];
|
||||
|
||||
pub fn hash_string(hash: ObjectHash) -> String {
|
||||
let mut result = String::new();
|
||||
for byte in hash {
|
||||
result.push_str(&format!("{:02x}", byte));
|
||||
}
|
||||
return result;
|
||||
hash.iter().fold(String::new(), |mut output, byte| {
|
||||
output.push_str(&format!("{byte:02x}"));
|
||||
output
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Tree {
|
||||
parent: Option<ObjectHash>,
|
||||
children: Vec<Object>,
|
||||
|
|
@ -48,6 +47,18 @@ enum Object {
|
|||
Blob(Blob),
|
||||
}
|
||||
|
||||
impl From<Tree> for Object {
|
||||
fn from(tree: Tree) -> Self {
|
||||
Self::Tree(tree)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Blob> for Object {
|
||||
fn from(blob: Blob) -> Self {
|
||||
Self::Blob(blob)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ObjDescription {
|
||||
pub hash: ObjectHash,
|
||||
pub path: String,
|
||||
|
|
@ -57,22 +68,22 @@ pub struct ObjDescription {
|
|||
impl Object {
|
||||
fn hash(&self) -> ObjectHash {
|
||||
match self {
|
||||
Object::Tree(tree) => tree.hash,
|
||||
Object::Blob(blob) => blob.hash,
|
||||
Self::Tree(tree) => tree.hash,
|
||||
Self::Blob(blob) => blob.hash,
|
||||
}
|
||||
}
|
||||
|
||||
fn path(&self) -> &String {
|
||||
match self {
|
||||
Object::Tree(tree) => &tree.path,
|
||||
Object::Blob(blob) => &blob.path,
|
||||
Self::Tree(tree) => &tree.path,
|
||||
Self::Blob(blob) => &blob.path,
|
||||
}
|
||||
}
|
||||
|
||||
fn json_for_obj(&self) -> String {
|
||||
match self {
|
||||
Object::Tree(tree) => tree.json_for_obj(),
|
||||
Object::Blob(blob) => blob.json_for_obj(),
|
||||
Self::Tree(tree) => tree.json_for_obj(),
|
||||
Self::Blob(blob) => blob.json_for_obj(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -80,15 +91,12 @@ impl Object {
|
|||
return ObjDescription {
|
||||
hash: self.hash(),
|
||||
path: self.path().clone(),
|
||||
is_blob: match self {
|
||||
Object::Tree(_) => false,
|
||||
Object::Blob(_) => true,
|
||||
},
|
||||
is_blob: matches!(self, Self::Blob(_)),
|
||||
};
|
||||
}
|
||||
|
||||
/// Return a tuple of (paths to add, paths to remove)
|
||||
fn diff(&self, new_obj: &Object) -> (Vec<ObjDescription>, Vec<ObjDescription>) {
|
||||
fn diff(&self, new_obj: &Self) -> (Vec<ObjDescription>, Vec<ObjDescription>) {
|
||||
let mut add: Vec<ObjDescription> = Vec::new();
|
||||
let mut remove: Vec<ObjDescription> = Vec::new();
|
||||
|
||||
|
|
@ -97,7 +105,7 @@ impl Object {
|
|||
}
|
||||
|
||||
match (self, new_obj) {
|
||||
(Object::Tree(old_tree), Object::Tree(new_tree)) => {
|
||||
(Self::Tree(old_tree), Self::Tree(new_tree)) => {
|
||||
// This is where you recurse like below
|
||||
let (child_add, child_remove) = old_tree.diff_children(new_tree);
|
||||
add.push(new_tree.descr());
|
||||
|
|
@ -105,23 +113,23 @@ impl Object {
|
|||
add.extend(child_add);
|
||||
remove.extend(child_remove);
|
||||
}
|
||||
(Object::Blob(old_blob), Object::Blob(new_blob)) => {
|
||||
(Self::Blob(old_blob), Self::Blob(new_blob)) => {
|
||||
add.push(new_blob.descr());
|
||||
remove.push(old_blob.descr());
|
||||
}
|
||||
(Object::Blob(old_blob), Object::Tree(new_tree)) => {
|
||||
(Self::Blob(old_blob), Self::Tree(new_tree)) => {
|
||||
// Remove blob, add entire new tree
|
||||
remove.push(old_blob.descr());
|
||||
add.extend(new_tree.all_obj_descriptions());
|
||||
}
|
||||
(Object::Tree(old_tree), Object::Blob(new_blob)) => {
|
||||
(Self::Tree(old_tree), Self::Blob(new_blob)) => {
|
||||
// Remove entire old tree, add blob
|
||||
remove.extend(old_tree.all_obj_descriptions());
|
||||
add.push(new_blob.descr());
|
||||
}
|
||||
}
|
||||
|
||||
return (add, remove);
|
||||
(add, remove)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -140,7 +148,7 @@ pub fn diff(old_tree: &Tree, new_tree: &Tree) -> (Vec<ObjDescription>, Vec<ObjDe
|
|||
add.extend(child_add);
|
||||
remove.extend(child_remove);
|
||||
|
||||
return (add, remove);
|
||||
(add, remove)
|
||||
}
|
||||
|
||||
impl Blob {
|
||||
|
|
@ -153,44 +161,45 @@ impl Blob {
|
|||
};
|
||||
|
||||
let mut json = serde_json::to_string(&node).unwrap();
|
||||
json.push_str("\n");
|
||||
return json;
|
||||
json.push('\n');
|
||||
json
|
||||
}
|
||||
|
||||
fn descr(&self) -> ObjDescription {
|
||||
return ObjDescription {
|
||||
ObjDescription {
|
||||
hash: self.hash,
|
||||
path: self.path.clone(),
|
||||
is_blob: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum DiffType {
|
||||
Add,
|
||||
Update,
|
||||
Remove,
|
||||
}
|
||||
// enum DiffType {
|
||||
// Add,
|
||||
// Update,
|
||||
// Remove,
|
||||
// }
|
||||
|
||||
impl Tree {
|
||||
fn descr(&self) -> ObjDescription {
|
||||
return ObjDescription {
|
||||
ObjDescription {
|
||||
hash: self.hash,
|
||||
path: self.path.clone(),
|
||||
is_blob: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn json_for_node(&self) -> String {
|
||||
let node = SerializeableNode {
|
||||
parent: self.parent,
|
||||
children: Some(self.children.iter().map(|child| child.hash()).collect()),
|
||||
children: Some(self.children.iter().map(Object::hash).collect()),
|
||||
hash: self.hash,
|
||||
path: self.path.clone(),
|
||||
};
|
||||
|
||||
let mut json = serde_json::to_string(&node).unwrap();
|
||||
json.push_str("\n");
|
||||
return json;
|
||||
json.push('\n');
|
||||
json
|
||||
}
|
||||
|
||||
fn json_for_obj(&self) -> String {
|
||||
|
|
@ -201,70 +210,63 @@ impl Tree {
|
|||
result.push_str(&child.json_for_obj());
|
||||
}
|
||||
|
||||
return result;
|
||||
result
|
||||
}
|
||||
|
||||
fn obj_from_jsonl(lines: &mut std::str::Lines, first_line: Option<SerializeableNode>) -> Tree {
|
||||
let root_node = match first_line {
|
||||
Some(line) => line,
|
||||
None => serde_json::from_str(lines.next().unwrap()).unwrap(),
|
||||
};
|
||||
fn obj_from_jsonl(lines: &mut std::str::Lines, first_line: Option<SerializeableNode>) -> Self {
|
||||
let root_node =
|
||||
first_line.unwrap_or_else(|| serde_json::from_str(lines.next().unwrap()).unwrap());
|
||||
|
||||
let mut children: Vec<Object> = Vec::new();
|
||||
for child_hash in root_node.children.unwrap() {
|
||||
let child_jsonl = lines.next().unwrap();
|
||||
let child_node: SerializeableNode = serde_json::from_str(child_jsonl).unwrap();
|
||||
match child_node.children {
|
||||
Some(_) => {
|
||||
let child = Tree::obj_from_jsonl(lines, Some(child_node));
|
||||
children.push(Object::Tree(child));
|
||||
}
|
||||
None => {
|
||||
let child = Blob {
|
||||
let children = root_node
|
||||
.children
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|_child_hash| {
|
||||
let child_jsonl = lines.next().unwrap();
|
||||
let child_node: SerializeableNode = serde_json::from_str(child_jsonl).unwrap();
|
||||
if child_node.children.is_some() {
|
||||
Self::obj_from_jsonl(lines, Some(child_node)).into()
|
||||
} else {
|
||||
Blob {
|
||||
parent: child_node.parent,
|
||||
hash: child_node.hash,
|
||||
path: child_node.path,
|
||||
};
|
||||
children.push(Object::Blob(child));
|
||||
}
|
||||
.into()
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
return Tree {
|
||||
Self {
|
||||
parent: root_node.parent,
|
||||
children,
|
||||
hash: root_node.hash,
|
||||
path: root_node.path,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Persist the tree to disk as JSONL
|
||||
pub fn persist(&self, filepath: &Path) {
|
||||
if let Some(dir) = filepath.parent() {
|
||||
std::fs::create_dir_all(dir)
|
||||
.expect(format!("Failed to create dir {}", dir.display()).as_str());
|
||||
.unwrap_or_else(|_| panic!("Failed to create dir {}", dir.display()));
|
||||
}
|
||||
let mut file = std::fs::File::create(filepath).unwrap();
|
||||
file.write_all(self.json_for_obj().as_bytes()).unwrap();
|
||||
}
|
||||
|
||||
/// Load the tree from JSONL file
|
||||
pub fn load(filepath: &Path) -> Result<Tree> {
|
||||
pub fn load(filepath: &Path) -> Result<Self> {
|
||||
let mut file = std::fs::File::open(filepath)?;
|
||||
let mut contents = String::new();
|
||||
file.read_to_string(&mut contents)?;
|
||||
let mut lines = contents.lines();
|
||||
return Ok(Tree::obj_from_jsonl(&mut lines, None));
|
||||
Ok(Self::obj_from_jsonl(&mut lines, None))
|
||||
}
|
||||
|
||||
pub fn empty() -> Tree {
|
||||
return Tree {
|
||||
parent: None,
|
||||
children: Vec::new(),
|
||||
hash: tree_hash(Vec::new()),
|
||||
path: String::new(),
|
||||
};
|
||||
}
|
||||
// pub fn empty() -> Self {
|
||||
// Self::default()
|
||||
// }
|
||||
|
||||
fn set_childrens_parent(&mut self) {
|
||||
for child in &mut self.children {
|
||||
|
|
@ -293,12 +295,12 @@ impl Tree {
|
|||
fn all_obj_descriptions(&self) -> Vec<ObjDescription> {
|
||||
let mut result = Vec::new();
|
||||
self.walk(&mut |obj| result.push(obj.descr()));
|
||||
return result;
|
||||
result
|
||||
}
|
||||
|
||||
/// Return a list of paths that have changed and the type of change (0 = add, 1 = update, 2 = remove)
|
||||
/// other is considered the "new" tree
|
||||
fn diff_children(&self, new_tree: &Tree) -> (Vec<ObjDescription>, Vec<ObjDescription>) {
|
||||
fn diff_children(&self, new_tree: &Self) -> (Vec<ObjDescription>, Vec<ObjDescription>) {
|
||||
let mut add = Vec::new();
|
||||
let mut remove = Vec::new();
|
||||
|
||||
|
|
@ -331,16 +333,16 @@ impl Tree {
|
|||
}
|
||||
|
||||
// Remove - along with all children
|
||||
for (path, obj) in old_path_to_object {
|
||||
for obj in old_path_to_object.values() {
|
||||
match obj {
|
||||
Object::Tree(tree) => tree.walk(&mut |obj| {
|
||||
Object::Tree(tree) => tree.walk(&mut |_obj| {
|
||||
remove.extend(tree.all_obj_descriptions());
|
||||
}),
|
||||
Object::Blob(_) => remove.push(obj.descr()),
|
||||
}
|
||||
}
|
||||
|
||||
return (add, remove);
|
||||
(add, remove)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -396,7 +398,7 @@ fn global_ignore_path() -> PathBuf {
|
|||
path.push(".continue");
|
||||
path.push("index");
|
||||
path.push(".globalcontinueignore");
|
||||
return path;
|
||||
path
|
||||
}
|
||||
|
||||
fn create_global_ignore_file() -> PathBuf {
|
||||
|
|
@ -407,11 +409,11 @@ fn create_global_ignore_file() -> PathBuf {
|
|||
let mut file = std::fs::File::create(path).unwrap();
|
||||
for pattern in GLOBAL_IGNORE_PATTERNS {
|
||||
file.write_all(pattern.as_bytes()).unwrap();
|
||||
file.write_all("\n".as_bytes()).unwrap();
|
||||
file.write_all(b"\n").unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
return global_ignore_path();
|
||||
global_ignore_path()
|
||||
}
|
||||
|
||||
pub fn build_walk(dir: &Path) -> Walk {
|
||||
|
|
@ -421,48 +423,43 @@ pub fn build_walk(dir: &Path) -> Walk {
|
|||
let builder = binding.add_custom_ignore_filename(".continueignore");
|
||||
|
||||
builder.add_ignore(path);
|
||||
return builder.build();
|
||||
builder.build()
|
||||
}
|
||||
|
||||
fn sha1_hash(content: &str) -> ObjectHash {
|
||||
let mut hasher = Sha1::new();
|
||||
hasher.update(content);
|
||||
let result = hasher.finalize();
|
||||
let hash_bytes: [u8; 20] = result.into();
|
||||
return hash_bytes;
|
||||
hasher.finalize().into()
|
||||
}
|
||||
|
||||
fn blob_hash(content: &str, file_ext: &str) -> ObjectHash {
|
||||
return sha1_hash(&format!("blob {} {}", file_ext, content));
|
||||
sha1_hash(&format!("blob {file_ext} {content}"))
|
||||
}
|
||||
|
||||
fn create_blob(filepath: &Path, parent: Option<ObjectHash>) -> Result<Blob> {
|
||||
let content = std::fs::read_to_string(filepath)?;
|
||||
let hash = blob_hash(
|
||||
&content,
|
||||
match filepath.extension() {
|
||||
Some(ext) => ext.to_str().unwrap(),
|
||||
None => "",
|
||||
},
|
||||
filepath.extension().map_or("", |ext| ext.to_str().unwrap()),
|
||||
);
|
||||
return Ok(Blob {
|
||||
parent: parent,
|
||||
hash: hash,
|
||||
Ok(Blob {
|
||||
parent,
|
||||
hash,
|
||||
path: filepath.to_str().unwrap().to_string(),
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
fn tree_hash(children: Vec<ObjectHash>) -> ObjectHash {
|
||||
fn tree_hash(children: impl IntoIterator<Item = ObjectHash>) -> ObjectHash {
|
||||
let mut hasher = Sha1::new();
|
||||
hasher.update("tree".as_bytes());
|
||||
hasher.update(b"tree");
|
||||
|
||||
// Note you're not just concatenating
|
||||
for child in &children {
|
||||
for child in children {
|
||||
hasher.update(child);
|
||||
}
|
||||
let result = hasher.finalize();
|
||||
let hash_bytes: [u8; 20] = result.into();
|
||||
return hash_bytes;
|
||||
hash_bytes
|
||||
}
|
||||
|
||||
struct PreTree {
|
||||
|
|
@ -475,7 +472,7 @@ impl PreTree {
|
|||
return Tree {
|
||||
parent: None,
|
||||
children: self.children.clone(),
|
||||
hash: tree_hash(self.children.iter().map(|child| child.hash()).collect()),
|
||||
hash: tree_hash(self.children.iter().map(Object::hash)),
|
||||
path: self.path.clone(),
|
||||
};
|
||||
}
|
||||
|
|
@ -483,7 +480,7 @@ impl PreTree {
|
|||
|
||||
/// Compute merkle tree and all sub-objects
|
||||
/// The last element in the vector is the root of the tree
|
||||
pub fn compute_tree_for_dir(dir: &Path, parent: Option<ObjectHash>) -> Result<Tree> {
|
||||
pub fn compute_tree_for_dir(dir: &Path, _parent: Option<ObjectHash>) -> Result<Tree> {
|
||||
let mut walk = build_walk(dir);
|
||||
let root_entry = walk
|
||||
.next() // This is just "."
|
||||
|
|
@ -536,7 +533,7 @@ pub fn compute_tree_for_dir(dir: &Path, parent: Option<ObjectHash>) -> Result<Tr
|
|||
.children
|
||||
.push(Object::Blob(blob));
|
||||
}
|
||||
Err(err) => {
|
||||
Err(_err) => {
|
||||
// Not UTF-8 formatted. Binary file. Ignore.
|
||||
}
|
||||
}
|
||||
|
|
@ -564,7 +561,7 @@ pub fn compute_tree_for_dir(dir: &Path, parent: Option<ObjectHash>) -> Result<Tr
|
|||
// Go through and update the parent of each child
|
||||
root_tree.set_childrens_parent();
|
||||
|
||||
return Ok(root_tree);
|
||||
Ok(root_tree)
|
||||
}
|
||||
|
||||
// Tests
|
||||
|
|
@ -643,9 +640,8 @@ mod tests {
|
|||
// Try adding a file at the root level
|
||||
let path = temp_dir.path().join("new_file.txt");
|
||||
fs::write(path, "42").expect("Failed to write to file");
|
||||
let tree_prime_prime = compute_tree_for_dir(temp_dir.path(), None)
|
||||
.expect("Failed to compute tree")
|
||||
.clone();
|
||||
let tree_prime_prime =
|
||||
compute_tree_for_dir(temp_dir.path(), None).expect("Failed to compute tree");
|
||||
|
||||
// Compare original and ''
|
||||
let (add, remove) = diff(&tree, &tree_prime_prime);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
mod merkle;
|
||||
use homedir::get_my_home;
|
||||
use merkle::{build_walk, compute_tree_for_dir, diff, hash_string, ObjectHash};
|
||||
use merkle::{compute_tree_for_dir, diff, hash_string};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::{self, File, OpenOptions},
|
||||
|
|
@ -36,15 +36,30 @@ fn remove_seps_from_path(dir: &Path) -> String {
|
|||
}
|
||||
|
||||
// Remove leading slash
|
||||
if path.starts_with("/") || path.starts_with("\\") {
|
||||
if path.starts_with('/') || path.starts_with('\\') {
|
||||
path.remove(0);
|
||||
}
|
||||
return path;
|
||||
path
|
||||
}
|
||||
|
||||
fn path_for_tag(tag: &Tag) -> PathBuf {
|
||||
let mut path = get_my_home().unwrap().unwrap();
|
||||
path.push(".continue/index/tags");
|
||||
<<<<<<<< HEAD:sync/src/sync.rs
|
||||
path.push(remove_seps_from_path(dir));
|
||||
if let Some(branch) = branch {
|
||||
path.push(branch);
|
||||
} else {
|
||||
path.push("main");
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
// /// Stored in ~/.continue/index/.last_sync
|
||||
// fn get_last_sync_time(dir: &Path, branch: Option<&str>) -> u64 {
|
||||
// // TODO: Error handle here
|
||||
// let path = path_for_tag(dir, branch).join(".last_sync");
|
||||
========
|
||||
path.push(remove_seps_from_path(tag.dir));
|
||||
path.push(tag.branch);
|
||||
path.push(tag.provider_id);
|
||||
|
|
@ -55,14 +70,14 @@ fn path_for_tag(tag: &Tag) -> PathBuf {
|
|||
fn get_last_sync_time(tag: &Tag) -> u64 {
|
||||
// TODO: Error handle here
|
||||
let path = path_for_tag(tag).join(".last_sync");
|
||||
>>>>>>>> preview:sync/src/sync/mod.rs
|
||||
|
||||
let mut file = File::open(path).unwrap();
|
||||
let mut contents = String::new();
|
||||
file.read_to_string(&mut contents).unwrap();
|
||||
// let mut file = File::open(path).unwrap();
|
||||
// let mut contents = String::new();
|
||||
// file.read_to_string(&mut contents).unwrap();
|
||||
|
||||
let last_sync_time = contents.parse::<u64>().unwrap();
|
||||
return last_sync_time;
|
||||
}
|
||||
// contents.parse::<u64>().unwrap()
|
||||
// }
|
||||
|
||||
fn write_sync_time(tag: &Tag) {
|
||||
let path = path_for_tag(tag).join(".last_sync");
|
||||
|
|
@ -75,6 +90,11 @@ fn write_sync_time(tag: &Tag) {
|
|||
file.write_all(now.to_string().as_bytes()).unwrap();
|
||||
}
|
||||
|
||||
<<<<<<<< HEAD:sync/src/sync.rs
|
||||
// /// Use stat to find files since last sync time
|
||||
// pub fn get_modified_files(dir: &Path, branch: Option<&str>) -> Vec<PathBuf> {
|
||||
// let last_sync_time = get_last_sync_time(dir, branch);
|
||||
========
|
||||
/// Use stat to find files since last sync time
|
||||
pub fn get_modified_files(tag: &Tag) -> Vec<PathBuf> {
|
||||
let last_sync_time = get_last_sync_time(tag);
|
||||
|
|
@ -84,14 +104,23 @@ pub fn get_modified_files(tag: &Tag) -> Vec<PathBuf> {
|
|||
let path = entry.path();
|
||||
let metadata = path.metadata().unwrap();
|
||||
let modified = metadata.modified().unwrap();
|
||||
>>>>>>>> preview:sync/src/sync/mod.rs
|
||||
|
||||
if modified.duration_since(UNIX_EPOCH).unwrap().as_secs() > last_sync_time {
|
||||
modified_files.push(path.to_path_buf().clone());
|
||||
}
|
||||
}
|
||||
// build_walk(dir)
|
||||
// .filter_map(|entry| {
|
||||
// let entry = entry.unwrap();
|
||||
// let path = entry.path();
|
||||
// let metadata = path.metadata().unwrap();
|
||||
// let modified = metadata.modified().unwrap();
|
||||
|
||||
return modified_files;
|
||||
}
|
||||
// if modified.duration_since(UNIX_EPOCH).unwrap().as_secs() > last_sync_time {
|
||||
// Some(path.to_path_buf())
|
||||
// } else {
|
||||
// None
|
||||
// }
|
||||
// })
|
||||
// .collect()
|
||||
// }
|
||||
|
||||
// Merkle trees are unique to directories, even if nested, but .index_cache is shared between all
|
||||
|
||||
|
|
@ -102,13 +131,13 @@ struct DiskSet {
|
|||
const ITEM_SIZE: usize = 20;
|
||||
|
||||
impl DiskSet {
|
||||
pub fn new(path: &str) -> DiskSet {
|
||||
pub fn new(path: &str) -> Self {
|
||||
let path = Path::new(path);
|
||||
if !path.exists() {
|
||||
File::create(path).unwrap();
|
||||
}
|
||||
|
||||
DiskSet {
|
||||
Self {
|
||||
file: OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
|
|
@ -179,7 +208,7 @@ impl<'a> IndexCache<'a> {
|
|||
fn index_cache_path_for_tag(tag: &Tag) -> PathBuf {
|
||||
let mut path = path_for_tag(tag);
|
||||
path.push(".index_cache");
|
||||
return path;
|
||||
path
|
||||
}
|
||||
|
||||
fn rev_tags_dir(provider_id: &str) -> PathBuf {
|
||||
|
|
@ -193,10 +222,33 @@ impl<'a> IndexCache<'a> {
|
|||
let mut path = IndexCache::rev_tags_dir(provider_id);
|
||||
// Branch by 1) first two chars of hash
|
||||
path.push(&hash_str[0..2]);
|
||||
return path;
|
||||
path
|
||||
}
|
||||
|
||||
fn tag_str(&self) -> String {
|
||||
<<<<<<<< HEAD:sync/src/sync.rs
|
||||
format!("{}::{}", self.dir.to_str().unwrap(), self.branch)
|
||||
}
|
||||
|
||||
fn new(dir: &Path, branch: Option<&str>) -> Self {
|
||||
Self {
|
||||
dir: Box::from(dir),
|
||||
branch: Box::from(branch.unwrap_or("main")),
|
||||
global_cache: DiskSet::new(
|
||||
get_my_home()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.join(".continue/index/.index_cache")
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
),
|
||||
tag_cache: DiskSet::new(
|
||||
Self::index_cache_path_for_tag(dir, branch.unwrap_or("main"))
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
),
|
||||
}
|
||||
========
|
||||
return self.tag.to_string();
|
||||
}
|
||||
|
||||
|
|
@ -218,6 +270,7 @@ impl<'a> IndexCache<'a> {
|
|||
),
|
||||
tag_cache: DiskSet::new(IndexCache::index_cache_path_for_tag(tag).to_str().unwrap()),
|
||||
};
|
||||
>>>>>>>> preview:sync/src/sync/mod.rs
|
||||
}
|
||||
|
||||
// rev_tags files are just json files with the following format:
|
||||
|
|
@ -225,29 +278,37 @@ impl<'a> IndexCache<'a> {
|
|||
|
||||
// TODO: You could add_bulk, remove_bulk if this gets slow
|
||||
|
||||
<<<<<<<< HEAD:sync/src/sync.rs
|
||||
fn read_rev_tags(hash: [u8; ITEM_SIZE]) -> HashMap<String, Vec<String>> {
|
||||
let rev_tags_path = Self::rev_tags_path(hash);
|
||||
========
|
||||
fn read_rev_tags(&self, hash: [u8; ITEM_SIZE]) -> HashMap<String, Vec<String>> {
|
||||
let rev_tags_path = IndexCache::rev_tags_path(hash, self.tag.provider_id);
|
||||
>>>>>>>> preview:sync/src/sync/mod.rs
|
||||
let mut rev_tags_file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.open(&rev_tags_path)
|
||||
.open(rev_tags_path)
|
||||
.unwrap();
|
||||
let mut contents = String::new();
|
||||
rev_tags_file.read_to_string(&mut contents).unwrap();
|
||||
let rev_tags: HashMap<String, Vec<String>> =
|
||||
serde_json::from_str(&contents).unwrap_or(HashMap::new());
|
||||
|
||||
return rev_tags;
|
||||
serde_json::from_str(&contents).unwrap_or_default()
|
||||
}
|
||||
|
||||
<<<<<<<< HEAD:sync/src/sync.rs
|
||||
fn write_rev_tags(hash: [u8; ITEM_SIZE], rev_tags: &HashMap<String, Vec<String>>) {
|
||||
let rev_tags_path = Self::rev_tags_path(hash);
|
||||
========
|
||||
fn write_rev_tags(&self, hash: [u8; ITEM_SIZE], rev_tags: HashMap<String, Vec<String>>) {
|
||||
let rev_tags_path = IndexCache::rev_tags_path(hash, self.tag.provider_id);
|
||||
>>>>>>>> preview:sync/src/sync/mod.rs
|
||||
let mut rev_tags_file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.open(&rev_tags_path)
|
||||
.open(rev_tags_path)
|
||||
.unwrap();
|
||||
let json = serde_json::to_string(&rev_tags).unwrap();
|
||||
|
||||
|
|
@ -263,14 +324,14 @@ impl<'a> IndexCache<'a> {
|
|||
self.tag_cache.add(&item.hash);
|
||||
|
||||
// Add to rev_tags
|
||||
let mut rev_tags = self.read_rev_tags(item.hash);
|
||||
let mut rev_tags = Self::read_rev_tags(item.hash);
|
||||
let tag_str = self.tag_str();
|
||||
let hash_str = hash_string(item.hash);
|
||||
if !rev_tags.contains_key(hash_str.as_str()) {
|
||||
rev_tags.insert(hash_str.clone(), Vec::new());
|
||||
}
|
||||
rev_tags.get_mut(hash_str.as_str()).unwrap().push(tag_str);
|
||||
self.write_rev_tags(item.hash, rev_tags);
|
||||
Self::write_rev_tags(item.hash, &rev_tags);
|
||||
}
|
||||
|
||||
fn global_remove(&mut self, item: &ObjDescription) {
|
||||
|
|
@ -278,48 +339,47 @@ impl<'a> IndexCache<'a> {
|
|||
self.tag_cache.remove(&item.hash);
|
||||
|
||||
// Remove from rev_tags
|
||||
let mut rev_tags = self.read_rev_tags(item.hash);
|
||||
let tag_str = self.tag_str();
|
||||
let mut rev_tags = Self::read_rev_tags(item.hash);
|
||||
let hash_str = hash_string(item.hash);
|
||||
if rev_tags.contains_key(hash_str.as_str()) {
|
||||
rev_tags.remove(hash_str.as_str());
|
||||
}
|
||||
self.write_rev_tags(item.hash, rev_tags);
|
||||
Self::write_rev_tags(item.hash, &rev_tags);
|
||||
}
|
||||
|
||||
fn local_remove(&mut self, item: &ObjDescription) {
|
||||
self.tag_cache.remove(&item.hash);
|
||||
|
||||
// Remove from rev_tags
|
||||
let mut rev_tags = self.read_rev_tags(item.hash);
|
||||
let mut rev_tags = Self::read_rev_tags(item.hash);
|
||||
let tag_str = self.tag_str();
|
||||
let hash_str = hash_string(item.hash);
|
||||
if rev_tags.contains_key(hash_str.as_str()) {
|
||||
let tags = rev_tags.get_mut(hash_str.as_str()).unwrap();
|
||||
let index = tags.iter().position(|x| *x == tag_str).unwrap();
|
||||
tags.remove(index);
|
||||
if tags.len() == 0 {
|
||||
if tags.is_empty() {
|
||||
rev_tags.remove(hash_str.as_str());
|
||||
}
|
||||
}
|
||||
self.write_rev_tags(item.hash, rev_tags);
|
||||
Self::write_rev_tags(item.hash, &rev_tags);
|
||||
}
|
||||
|
||||
fn global_contains(&mut self, hash: &[u8; ITEM_SIZE]) -> bool {
|
||||
self.global_cache.contains(hash)
|
||||
}
|
||||
|
||||
fn tag_contains(&mut self, hash: &[u8; ITEM_SIZE]) -> bool {
|
||||
self.tag_cache.contains(&hash)
|
||||
}
|
||||
// fn tag_contains(&mut self, hash: &[u8; ITEM_SIZE]) -> bool {
|
||||
// self.tag_cache.contains(hash)
|
||||
// }
|
||||
|
||||
fn get_rev_tags(&self, hash: &[u8; ITEM_SIZE]) -> Vec<String> {
|
||||
let mut rev_tags = self.read_rev_tags(*hash);
|
||||
fn get_rev_tags(hash: &[u8; ITEM_SIZE]) -> Vec<String> {
|
||||
let mut rev_tags = Self::read_rev_tags(*hash);
|
||||
let hash_str = hash_string(*hash);
|
||||
if rev_tags.contains_key(hash_str.as_str()) {
|
||||
return rev_tags.remove(hash_str.as_str()).unwrap();
|
||||
rev_tags.remove(hash_str.as_str()).unwrap()
|
||||
} else {
|
||||
return Vec::new();
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -344,10 +404,8 @@ pub fn sync(
|
|||
|
||||
let mut tree_path = path_for_tag(tag);
|
||||
tree_path.push("merkle_tree");
|
||||
let old_tree: Tree = match Tree::load(&tree_path) {
|
||||
Ok(tree) => tree,
|
||||
Err(_) => Tree::empty(),
|
||||
};
|
||||
|
||||
let old_tree = Tree::load(&tree_path).unwrap_or_default();
|
||||
|
||||
// Calculate and save new tree
|
||||
// TODO: Use modified files to speed up calculation
|
||||
|
|
@ -399,7 +457,7 @@ pub fn sync(
|
|||
continue;
|
||||
}
|
||||
if index_cache.global_contains(&item.hash) {
|
||||
if index_cache.get_rev_tags(&item.hash).len() <= 1 {
|
||||
if IndexCache::get_rev_tags(&item.hash).len() <= 1 {
|
||||
// If it's cached only for this tag, remove it from the global cache as well
|
||||
index_cache.global_remove(&item);
|
||||
let hash = hash_string(item.hash);
|
||||
|
|
@ -417,13 +475,13 @@ pub fn sync(
|
|||
}
|
||||
}
|
||||
|
||||
return Ok((compute, delete, add_label, remove_label));
|
||||
Ok((compute, delete, add_label, remove_label))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::utils::TempDirBuilder;
|
||||
use crate::{sync::merkle::ObjectHash, utils::TempDirBuilder};
|
||||
use std::fs::remove_file;
|
||||
|
||||
#[test]
|
||||
|
|
@ -474,23 +532,37 @@ mod tests {
|
|||
#[test]
|
||||
fn test_sync() {
|
||||
let ti = std::time::Instant::now();
|
||||
<<<<<<<< HEAD:sync/src/sync.rs
|
||||
let _results = sync(
|
||||
Path::new("/Users/natesesti/Desktop/continue"),
|
||||
Some("nate/pyO3"),
|
||||
);
|
||||
========
|
||||
let tag = Tag {
|
||||
dir: Path::new("../"),
|
||||
branch: "nate/pyO3",
|
||||
provider_id: "default",
|
||||
};
|
||||
let results = sync(&tag);
|
||||
>>>>>>>> preview:sync/src/sync/mod.rs
|
||||
println!("Sync took {:?}", ti.elapsed());
|
||||
// Vast majority (90+%) of this time is spent in compute_tree_for_dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_on_vscode_extension() {
|
||||
<<<<<<<< HEAD:sync/src/sync.rs
|
||||
let _results = sync(
|
||||
Path::new("/Users/natesesti/Desktop/continue/extensions/vscode"),
|
||||
Some("nate/pyO3"),
|
||||
);
|
||||
========
|
||||
let results = sync(&Tag {
|
||||
dir: Path::new("../extensions/vscode"),
|
||||
branch: "nate/pyO3",
|
||||
provider_id: "default",
|
||||
});
|
||||
>>>>>>>> preview:sync/src/sync/mod.rs
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -503,8 +575,8 @@ mod tests {
|
|||
})
|
||||
.expect("Sync failed.");
|
||||
println!("First sync took {:?}", ti.elapsed());
|
||||
assert!(results.0.len() > 0);
|
||||
assert!(results.1.len() > 0);
|
||||
assert!(!results.0.is_empty());
|
||||
assert!(!results.1.is_empty());
|
||||
|
||||
let ti = std::time::Instant::now();
|
||||
let results = sync(&Tag {
|
||||
|
|
@ -539,9 +611,9 @@ mod tests {
|
|||
|
||||
// Make changes
|
||||
let mut file = File::create(temp_dir.path().join("dir1/file1.txt")).unwrap();
|
||||
file.write_all("File 1 changed".as_bytes()).unwrap();
|
||||
file.write_all(b"File 1 changed").unwrap();
|
||||
let mut file = File::create(temp_dir.path().join("dir2/file3.txt")).unwrap();
|
||||
file.write_all("File 3 changed".as_bytes()).unwrap();
|
||||
file.write_all(b"File 3 changed").unwrap();
|
||||
|
||||
// Sync again
|
||||
let results = sync(tag).expect("Sync failed.");
|
||||
|
|
|
|||
34
sync/src/utils.rs
Normal file
34
sync/src/utils.rs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct TempDirBuilder {
|
||||
files: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl TempDirBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn add(&mut self, path: &str, content: &str) -> &mut Self {
|
||||
self.files.push((path.to_string(), content.to_string()));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn create(&self) -> tempfile::TempDir {
|
||||
let temp_dir = tempdir().expect("Failed to create temp dir");
|
||||
|
||||
for (path, content) in &self.files {
|
||||
let file_path = temp_dir.path().join(path);
|
||||
if let Some(dir) = file_path.parent() {
|
||||
fs::create_dir_all(dir).expect("Failed to create directory");
|
||||
}
|
||||
let mut file = File::create(&file_path).expect("Failed to create test file");
|
||||
writeln!(file, "{content}").expect("Failed to write to test file");
|
||||
}
|
||||
|
||||
temp_dir
|
||||
}
|
||||
}
|
||||
|
|
@ -2,18 +2,19 @@ use std::fs::{self, File};
|
|||
use std::io::Write;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct TempDirBuilder {
|
||||
files: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl TempDirBuilder {
|
||||
pub fn new() -> TempDirBuilder {
|
||||
return TempDirBuilder { files: Vec::new() };
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn add(&mut self, path: &str, content: &str) -> &mut TempDirBuilder {
|
||||
pub fn add(&mut self, path: &str, content: &str) -> &mut Self {
|
||||
self.files.push((path.to_string(), content.to_string()));
|
||||
return self;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn create(&self) -> tempfile::TempDir {
|
||||
|
|
@ -25,9 +26,9 @@ impl TempDirBuilder {
|
|||
fs::create_dir_all(dir).expect("Failed to create directory");
|
||||
}
|
||||
let mut file = File::create(&file_path).expect("Failed to create test file");
|
||||
writeln!(file, "{}", content).expect("Failed to write to test file");
|
||||
writeln!(file, "{content}").expect("Failed to write to test file");
|
||||
}
|
||||
|
||||
return temp_dir;
|
||||
temp_dir
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue