ki-brain / src /github.cpp
Arian8888's picture
GitHub als Source of Truth: Pull beim Start + Auto-Commit bei jedem Write
df43f32
Raw History Blame Contribute Delete
10.6 kB
#include "github.h"
#include <curl/curl.h>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <mutex>
#include <unordered_map>
namespace gh {
static std::string g_token;
static std::string g_repo; // "Owner/Repo"
static std::mutex g_mtx;
static std::unordered_map<std::string, std::string> g_sha_cache; // path -> sha
void init() {
const char* t = std::getenv("GITHUB_TOKEN");
const char* r = std::getenv("GITHUB_REPO");
g_token = t ? t : "";
g_repo = r ? r : "Arian8888/ki-brain-data";
if (!g_token.empty())
std::cout << "[github] Sync aktiv: " << g_repo << std::endl;
else
std::cout << "[github] kein GITHUB_TOKEN -> Sync deaktiviert" << std::endl;
}
bool enabled() { return !g_token.empty(); }
// ────── Base64 ──────
static const char B64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static std::string base64_encode(const std::string& in) {
std::string out;
int val = 0, valb = -6;
for (unsigned char c : in) {
val = (val<<8) + c;
valb += 8;
while (valb >= 0) {
out.push_back(B64[(val>>valb) & 0x3F]);
valb -= 6;
}
}
if (valb > -6) out.push_back(B64[((val<<8) >> (valb+8)) & 0x3F]);
while (out.size() % 4) out.push_back('=');
return out;
}
// ────── HTTP Helpers ──────
static size_t write_cb(char* ptr, size_t size, size_t nmemb, void* ud) {
auto* s = (std::string*)ud;
s->append(ptr, size * nmemb);
return size * nmemb;
}
static std::string json_escape(const std::string& s) {
std::string o; o.reserve(s.size() + 8);
for (unsigned char c : s) {
switch (c) {
case '"': o += "\\\""; break;
case '\\': o += "\\\\"; break;
case '\n': o += "\\n"; break;
case '\r': o += "\\r"; break;
case '\t': o += "\\t"; break;
default:
if (c < 0x20) { char b[8]; std::snprintf(b, sizeof(b), "\\u%04x", c); o += b; }
else o += (char)c;
}
}
return o;
}
// extract simple JSON string value: "key":"value"
static std::string extract_json_string(const std::string& body, const std::string& key) {
std::string needle = "\"" + key + "\"";
size_t p = body.find(needle);
if (p == std::string::npos) return "";
p = body.find(':', p);
if (p == std::string::npos) return "";
p = body.find('"', p);
if (p == std::string::npos) return "";
++p;
std::string out;
while (p < body.size() && body[p] != '"') {
if (body[p] == '\\' && p+1 < body.size()) { out += body[p+1]; p += 2; }
else { out += body[p++]; }
}
return out;
}
// GET existing SHA for a path (if file exists). Returns empty if not found.
static std::string fetch_existing_sha(const std::string& path) {
{
std::lock_guard<std::mutex> lk(g_mtx);
auto it = g_sha_cache.find(path);
if (it != g_sha_cache.end()) return it->second;
}
CURL* c = curl_easy_init();
if (!c) return "";
std::string url = "https://api.github.com/repos/" + g_repo + "/contents/" + path;
std::string out;
struct curl_slist* hdr = nullptr;
hdr = curl_slist_append(hdr, ("Authorization: token " + g_token).c_str());
hdr = curl_slist_append(hdr, "User-Agent: KI-Brain-Sync");
hdr = curl_slist_append(hdr, "Accept: application/vnd.github+json");
curl_easy_setopt(c, CURLOPT_URL, url.c_str());
curl_easy_setopt(c, CURLOPT_HTTPHEADER, hdr);
curl_easy_setopt(c, CURLOPT_TIMEOUT, 10L);
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, write_cb);
curl_easy_setopt(c, CURLOPT_WRITEDATA, &out);
curl_easy_perform(c);
long code = 0;
curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &code);
curl_slist_free_all(hdr);
curl_easy_cleanup(c);
if (code != 200) return "";
std::string sha = extract_json_string(out, "sha");
if (!sha.empty()) {
std::lock_guard<std::mutex> lk(g_mtx);
g_sha_cache[path] = sha;
}
return sha;
}
bool put_file(const std::string& path, const std::string& content, const std::string& commit_msg) {
if (!enabled()) return false;
std::string sha = fetch_existing_sha(path);
std::string b64 = base64_encode(content);
std::string body = "{\"message\":\"" + json_escape(commit_msg) +
"\",\"content\":\"" + b64 + "\"";
if (!sha.empty()) body += ",\"sha\":\"" + sha + "\"";
body += "}";
CURL* c = curl_easy_init();
if (!c) return false;
std::string url = "https://api.github.com/repos/" + g_repo + "/contents/" + path;
std::string resp;
struct curl_slist* hdr = nullptr;
hdr = curl_slist_append(hdr, ("Authorization: token " + g_token).c_str());
hdr = curl_slist_append(hdr, "User-Agent: KI-Brain-Sync");
hdr = curl_slist_append(hdr, "Accept: application/vnd.github+json");
hdr = curl_slist_append(hdr, "Content-Type: application/json");
curl_easy_setopt(c, CURLOPT_URL, url.c_str());
curl_easy_setopt(c, CURLOPT_HTTPHEADER, hdr);
curl_easy_setopt(c, CURLOPT_CUSTOMREQUEST, "PUT");
curl_easy_setopt(c, CURLOPT_POSTFIELDS, body.c_str());
curl_easy_setopt(c, CURLOPT_TIMEOUT, 15L);
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, write_cb);
curl_easy_setopt(c, CURLOPT_WRITEDATA, &resp);
CURLcode rc = curl_easy_perform(c);
long code = 0;
curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &code);
curl_slist_free_all(hdr);
curl_easy_cleanup(c);
if (rc != CURLE_OK) {
std::cerr << "[github] PUT " << path << " curl error: " << curl_easy_strerror(rc) << std::endl;
return false;
}
if (code < 200 || code >= 300) {
std::cerr << "[github] PUT " << path << " HTTP " << code << ": " << resp.substr(0, 200) << std::endl;
return false;
}
// Aktualisierter SHA fuer die naechste Update-Operation
std::string new_sha = extract_json_string(resp, "sha");
if (!new_sha.empty()) {
std::lock_guard<std::mutex> lk(g_mtx);
g_sha_cache[path] = new_sha;
}
std::cout << "[github] +" << path << " (HTTP " << code << ")" << std::endl;
return true;
}
// Base64-decode fΓΌr get_file
static std::string base64_decode(const std::string& in) {
std::string out;
int T[256]; for (int i = 0; i < 256; ++i) T[i] = -1;
for (int i = 0; i < 64; ++i) T[(unsigned char)B64[i]] = i;
int val = 0, valb = -8;
for (unsigned char c : in) {
if (c == '\n' || c == '\r' || c == ' ') continue;
if (T[c] == -1) break;
val = (val<<6) + T[c];
valb += 6;
if (valb >= 0) { out.push_back(char((val>>valb) & 0xFF)); valb -= 8; }
}
return out;
}
std::string get_file(const std::string& path) {
if (!enabled()) return "";
CURL* c = curl_easy_init();
if (!c) return "";
std::string url = "https://api.github.com/repos/" + g_repo + "/contents/" + path;
std::string out;
struct curl_slist* hdr = nullptr;
hdr = curl_slist_append(hdr, ("Authorization: token " + g_token).c_str());
hdr = curl_slist_append(hdr, "User-Agent: KI-Brain-Sync");
hdr = curl_slist_append(hdr, "Accept: application/vnd.github+json");
curl_easy_setopt(c, CURLOPT_URL, url.c_str());
curl_easy_setopt(c, CURLOPT_HTTPHEADER, hdr);
curl_easy_setopt(c, CURLOPT_TIMEOUT, 10L);
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, write_cb);
curl_easy_setopt(c, CURLOPT_WRITEDATA, &out);
curl_easy_perform(c);
long code = 0;
curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &code);
curl_slist_free_all(hdr);
curl_easy_cleanup(c);
if (code != 200) return "";
// content is base64-encoded in response
std::string content_b64 = extract_json_string(out, "content");
// GitHub liefert mit \n - rausfiltern
std::string clean;
for (char ch : content_b64) if (ch != '\n' && ch != '\r' && ch != '\\') clean += ch;
return base64_decode(clean);
}
// Rekursiv brain/ Ordner aus GitHub holen
static void list_recurse(const std::string& path, std::vector<RemoteEntry>& out) {
CURL* c = curl_easy_init();
if (!c) return;
std::string url = "https://api.github.com/repos/" + g_repo + "/contents/" + path;
std::string body;
struct curl_slist* hdr = nullptr;
hdr = curl_slist_append(hdr, ("Authorization: token " + g_token).c_str());
hdr = curl_slist_append(hdr, "User-Agent: KI-Brain-Sync");
hdr = curl_slist_append(hdr, "Accept: application/vnd.github+json");
curl_easy_setopt(c, CURLOPT_URL, url.c_str());
curl_easy_setopt(c, CURLOPT_HTTPHEADER, hdr);
curl_easy_setopt(c, CURLOPT_TIMEOUT, 15L);
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, write_cb);
curl_easy_setopt(c, CURLOPT_WRITEDATA, &body);
curl_easy_perform(c);
long code = 0;
curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &code);
curl_slist_free_all(hdr);
curl_easy_cleanup(c);
if (code != 200) return;
// Parse Array: jedes Objekt hat "path":"...","type":"file"|"dir"
size_t pos = 0;
while (true) {
size_t pPath = body.find("\"path\":\"", pos);
if (pPath == std::string::npos) break;
pPath += 8;
size_t pEnd = body.find('"', pPath);
if (pEnd == std::string::npos) break;
std::string entryPath = body.substr(pPath, pEnd - pPath);
size_t pType = body.find("\"type\":\"", pEnd);
if (pType == std::string::npos) break;
pType += 8;
size_t tEnd = body.find('"', pType);
std::string type = body.substr(pType, tEnd - pType);
pos = tEnd + 1;
// entryPath like "brain/rules/admin.md" - strip "brain/" prefix
std::string relPath = entryPath;
const std::string prefix = "brain/";
if (relPath.rfind(prefix, 0) == 0) relPath = relPath.substr(prefix.size());
if (type == "dir") {
RemoteEntry e; e.path = relPath; e.is_dir = 1; e.content = "";
out.push_back(e);
list_recurse(entryPath, out);
} else if (type == "file") {
RemoteEntry e; e.path = relPath; e.is_dir = 0;
e.content = get_file(entryPath);
out.push_back(e);
}
}
}
std::vector<RemoteEntry> pull_brain() {
std::vector<RemoteEntry> result;
if (!enabled()) return result;
std::cout << "[github] pulling brain/ from " << g_repo << " ..." << std::endl;
list_recurse("brain", result);
std::cout << "[github] pulled " << result.size() << " entries" << std::endl;
return result;
}
} // namespace gh