Created
February 24, 2025 08:45
-
-
Save olejorgenb/d164c81fdefed97bcb0ca13210b3e3ff to your computer and use it in GitHub Desktop.
Generate cody file references
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Ref: https://community.sourcegraph.com/t/create-custom-prompt-programmatically/2189/3?u=olejorgenb | |
Likely this only works for Enterprise, but migh be possible to adjust for Pro if the web-interface is available. | |
""" | |
import base64 | |
import json | |
import sys | |
import urllib | |
import urllib.parse | |
from os import path | |
from pathlib import Path | |
from sunstone.slib import env | |
def make_file_reference(file_path: str): | |
source_graph_repo_url = "..." | |
repo_name = "..." | |
if path.isabs(file_path): | |
file_path = Path(__file__).relative_to(env.get_repository_root_path()).as_posix() | |
file_name = path.basename(file_path) | |
ref = { | |
"contextItem": { | |
"type": "openctx", | |
"uri": f"{source_graph_repo_url}/{file_path}", | |
"title": f"{file_path}", | |
"providerUri": "internal-remote-file-search", | |
"provider": "openctx", | |
"mention": { | |
"uri": f"{source_graph_repo_url}/{file_path}", | |
"data": { | |
"repoName": f"{repo_name}", | |
# "rev": "...", # When copying, the revision is included, but everything works if we omit it as well | |
"filePath": f"{file_path}", | |
}, | |
"description": f"{file_path}", | |
}, | |
"source": "user", | |
}, | |
"isFromInitialContext": False, | |
"type": "contextItemMention", | |
"text": f"{file_name}", | |
"version": 1, | |
} | |
return ref | |
def base64_encode(text: str) -> str: | |
"""Base64 encode a utf-8 encoded string, and return the encoding as a utf-8 string without line breaks""" | |
return "".join(base64.encodebytes(text.encode()).decode().split("\n")) | |
def encode_reference(ref: dict) -> str: | |
""" | |
Encode the reference in the format understood by https://$INSTANCE.sourcegraphcloud.com/prompts/ | |
Pasting the resulting text will be correctlyh interpreted once the prompt is saved. | |
""" | |
url_encoded = urllib.parse.quote(json.dumps(ref)) | |
return f"cody://serialized.v1?data={base64_encode(url_encoded)}_" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment