Skip to content

A visual git client, simple to use yet powerful. Light, fast and debloated.

Rust

feat: gitcraft 0.2.1 - VS Code code colours, count badges, darker pills

Iván84b659dd44cd
diff --git a/Cargo.lock b/Cargo.lock
index f65e9c3..4583ed2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1447,7 +1447,7 @@ dependencies = [
[[package]]
name = "gitcraft"
-version = "0.2.0"
+version = "0.2.1"
dependencies = [
"eframe",
"egui",
diff --git a/Cargo.toml b/Cargo.toml
index 1f4839b..6fa0bf0 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "gitcraft"
-version = "0.2.0"
+version = "0.2.1"
edition = "2024"
rust-version = "1.95"
license = "MIT OR Apache-2.0"
diff --git a/README.md b/README.md
index ce3c614..3945e72 100644
--- a/README.md
+++ b/README.md
@@ -23,7 +23,7 @@ so your config, credentials and hooks apply as usual.
it at that commit (`x` and `origin/x` make one pill), a pull-request icon when one is open,
`+N` when more refs share the commit, the author's avatar and how long ago it was ("2 hours
ago"). Author, date and hash columns are optional (Settings).
-- The checked-out branch's pill is solid, the others slightly see-through. Double-click a pill to
+- The checked-out branch's pill is solid, the others a darker shade. Double-click a pill to
check that branch (or tag) out; hover `+N` to list every pill of the commit and double-click
the one you want.
- An *Uncommitted changes* row on top while the working tree is dirty.
@@ -64,6 +64,8 @@ so your config, credentials and hooks apply as usual.
**Diffs and conflicts** (centre)
- Unified or side by side, syntax colours, the changed part of each line marked, whitespace
changes optional, images shown before / after. Esc closes.
+- Code takes the colours of the theme VS Code (or Insiders, VSCodium) is using, read from its
+ settings and extensions, when it is dark or light like gitcraft's; a setting turns it off.
- Conflicts open in a three-pane editor: each conflict's two sides with *Ours*, *Theirs* and
*Both* buttons, and the result below (editable). *Use mine* / *Use theirs* for a whole file.
- A merge, rebase, cherry-pick or revert stopped on conflicts shows a banner with *Abort*; the
@@ -152,6 +154,7 @@ was made this way, on a demo repository.
| `src/repo/detail.rs` | commit / stash detail, changes and commit box |
| `src/repo/diff.rs` | diff loading, pairing and the diff view (unified, split, images) |
| `src/repo/highlight.rs` | syntax colours (syntect) |
+| `src/vscode_theme.rs` | VS Code's current colour theme as a syntect theme |
| `src/repo/conflict.rs` | three-pane conflict editor |
| `src/repo/rebase.rs` | interactive rebase editor and its todo list |
| `src/repo/file_view.rs` | a file's history and blame |
diff --git a/src/icons.rs b/src/icons.rs
index 2bfcf01..8d1bb6a 100644
--- a/src/icons.rs
+++ b/src/icons.rs
@@ -93,6 +93,17 @@ pub fn paint(ui: &Ui, rect: Rect, name: &str, size: f32, tint: Color32) {
/// A flat toolbar button: icon plus optional label, background only on hover (PhotoCraft's
/// options-bar buttons).
pub fn tool_button(ui: &mut Ui, icon: &str, label: &str, enabled: bool) -> Response {
+ tool_button_count(ui, icon, label, 0, enabled)
+}
+
+/// A toolbar button with `count` in a circle after its label (none when 0).
+pub fn tool_button_count(
+ ui: &mut Ui,
+ icon: &str,
+ label: &str,
+ count: u32,
+ enabled: bool,
+) -> Response {
// Painted by hand at a fixed size: egui's button adds its border's width only while the
// frame shows, so hovering one pushed the rest of the toolbar sideways.
const PAD: f32 = 10.0;
@@ -105,8 +116,23 @@ pub fn tool_button(ui: &mut Ui, icon: &str, label: &str, enabled: bool) -> Respo
let font = egui::TextStyle::Button.resolve(ui.style());
ui.painter().layout_no_wrap(label.to_owned(), font, color)
});
+ const BADGE: f32 = 16.0;
+ let badge = (count > 0).then(|| {
+ let text = if count > 99 {
+ "99+".to_owned()
+ } else {
+ count.to_string()
+ };
+ let galley = ui
+ .painter()
+ .layout_no_wrap(text, crate::theme::semibold(10.0), t.accent_text);
+ // A circle for one digit, stretched into a pill for more.
+ let width = (galley.size().x + 8.0).max(BADGE);
+ (galley, width)
+ });
+ let badge_width = badge.as_ref().map_or(0.0, |(_, w)| GAP + w);
let width = match &galley {
- Some(g) => PAD + ICON + GAP + g.size().x + PAD,
+ Some(g) => PAD + ICON + GAP + g.size().x + badge_width + PAD,
None => 28.0,
};
ui.add_enabled(enabled, |ui: &mut Ui| {
@@ -135,7 +161,18 @@ pub fn tool_button(ui: &mut Ui, icon: &str, label: &str, enabled: bool) -> Respo
paint(ui, icon_rect, icon, ICON, tint);
if let Some(g) = galley {
let pos = egui::pos2(icon_rect.right() + GAP, rect.center().y - g.size().y / 2.0);
+ let text_right = pos.x + g.size().x;
ui.painter().galley(pos, g, color);
+ if let Some((count, w)) = badge {
+ let pill = Rect::from_min_size(
+ egui::pos2(text_right + GAP, rect.center().y - BADGE / 2.0),
+ Vec2::new(w, BADGE),
+ );
+ let fill = if enabled { t.accent } else { t.text_faint };
+ ui.painter().rect_filled(pill, BADGE / 2.0, fill);
+ ui.painter()
+ .galley(pill.center() - count.size() / 2.0, count, t.accent_text);
+ }
}
resp
})
diff --git a/src/lib.rs b/src/lib.rs
index 2256c8b..a445980 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -11,3 +11,4 @@ mod settings;
mod terminal;
mod theme;
mod update;
+mod vscode_theme;
diff --git a/src/repo/graph_view.rs b/src/repo/graph_view.rs
index 8fcb88a..0e28d21 100644
--- a/src/repo/graph_view.rs
+++ b/src/repo/graph_view.rs
@@ -19,6 +19,8 @@ use crate::theme::{self, Tokens};
const ROW_H: f32 = 28.0;
const LANE_W: f32 = 16.0;
const MAX_LANES_SHOWN: usize = 24;
+/// How much darker the pills that are not checked out are (0 = same colour, 1 = black).
+const DIMMED: f32 = 0.4;
const AUTHOR_W: f32 = 150.0;
const DATE_W: f32 = 118.0;
const HASH_W: f32 = 70.0;
@@ -638,7 +640,7 @@ impl RepoTab {
CornerRadius::same(t.radius as u8),
row_color
.lerp_to_gamma(Color32::BLACK, 0.35)
- .gamma_multiply(0.6),
+ .lerp_to_gamma(Color32::BLACK, DIMMED),
);
rp.text(
r.center(),
@@ -968,11 +970,11 @@ fn ref_pill(
BadgeKind::Tag => Color32::from_rgb(104, 104, 112),
BadgeKind::DetachedHead => t.warning,
};
- // Every pill but the checked-out one is a little see-through.
+ // Every pill but the checked-out one is a darker shade of its colour.
let fill = if badge.head {
fill
} else {
- fill.gamma_multiply(0.6)
+ fill.lerp_to_gamma(Color32::BLACK, DIMMED)
};
let mut lead = Vec::new();
let mut trail = Vec::new();
diff --git a/src/repo/highlight.rs b/src/repo/highlight.rs
index 3ae88c0..fa3bbcc 100644
--- a/src/repo/highlight.rs
+++ b/src/repo/highlight.rs
@@ -41,12 +41,19 @@ pub fn highlight<'a>(
if syntax.name == "Plain Text" {
return None;
}
- let theme_name = if dark {
- "base16-ocean.dark"
- } else {
- "InspiredGitHub"
+ // VS Code's theme when it suits the background: a dark theme on a light gitcraft reads badly.
+ let editor = crate::vscode_theme::enabled()
+ .then(crate::vscode_theme::current)
+ .flatten()
+ .filter(|e| e.dark == dark);
+ let theme = match &editor {
+ Some(e) => &e.theme,
+ None => themes().themes.get(if dark {
+ "base16-ocean.dark"
+ } else {
+ "InspiredGitHub"
+ })?,
};
- let theme = themes().themes.get(theme_name)?;
let mut h = HighlightLines::new(syntax, theme);
let mut out = Vec::new();
for line in lines {
diff --git a/src/repo/mod.rs b/src/repo/mod.rs
index 1a3c34b..42c940a 100644
--- a/src/repo/mod.rs
+++ b/src/repo/mod.rs
@@ -1770,26 +1770,19 @@ impl RepoTab {
.and_then(|c| self.refs.local.iter().find(|b| &b.name == c))
.map(|b| b.ahead_behind())
.unwrap_or((0, 0));
- let pull_label = if behind > 0 {
- format!("Pull {behind}")
- } else {
- "Pull".to_owned()
- };
- let pull =
- icons::tool_button(ui, "arrow-down-to-line", &pull_label, idle && has_remote)
- .on_hover_text("Fast-forward the current branch (git pull --ff-only)");
- if behind > 0 {
- widgets::count_badge(ui, pull.rect, t.accent);
- }
- if pull.clicked() {
+ if icons::tool_button_count(
+ ui,
+ "arrow-down-to-line",
+ "Pull",
+ behind,
+ idle && has_remote,
+ )
+ .on_hover_text("Fast-forward the current branch (git pull --ff-only)")
+ .clicked()
+ {
acts.push(Action::Pull);
}
- let push_label = if ahead > 0 {
- format!("Push {ahead}")
- } else {
- "Push".to_owned()
- };
- if icons::tool_button(ui, "arrow-up-from-line", &push_label, idle && has_remote)
+ if icons::tool_button_count(ui, "arrow-up-from-line", "Push", ahead, idle && has_remote)
.on_hover_text("Push the current branch (publishes it if it has no upstream yet)")
.clicked()
{
diff --git a/src/repo/widgets.rs b/src/repo/widgets.rs
index b8fc4b4..6a0d379 100644
--- a/src/repo/widgets.rs
+++ b/src/repo/widgets.rs
@@ -368,12 +368,6 @@ fn name_hash(name: &str) -> usize {
.fold(7usize, |h, b| h.wrapping_mul(31).wrapping_add(b as usize))
}
-/// A dot on the top-right corner of a toolbar button (incoming commits…).
-pub fn count_badge(ui: &Ui, button: Rect, color: Color32) {
- ui.painter()
- .circle_filled(button.right_top() + vec2(-5.0, 6.0), 3.5, color);
-}
-
/// The accent line under an active toolbar toggle.
pub fn active_underline(ui: &Ui, button: Rect, color: Color32) {
ui.painter().line_segment(
diff --git a/src/settings.rs b/src/settings.rs
index 7cb1179..a872c8e 100644
--- a/src/settings.rs
+++ b/src/settings.rs
@@ -38,6 +38,8 @@ pub struct Settings {
pub notifications: bool,
/// Ask GitHub once a day whether a newer release exists.
pub check_updates: bool,
+ /// Colour code in diffs and blame with VS Code's current theme, when it has one.
+ pub vscode_colors: bool,
pub profiles: Vec<Profile>,
}
@@ -56,6 +58,7 @@ impl Default for Settings {
editor: "code".to_owned(),
notifications: true,
check_updates: true,
+ vscode_colors: true,
profiles: Vec::new(),
}
}
@@ -74,6 +77,7 @@ impl Settings {
pub fn set(&self, ctx: &egui::Context) {
ctx.data_mut(|d| d.insert_temp(id(), self.clone()));
ctx.set_zoom_factor(self.ui_scale.clamp(0.7, 2.0));
+ crate::vscode_theme::set_enabled(self.vscode_colors);
}
/// The settings form. Returns true when something changed.
@@ -109,6 +113,23 @@ impl Settings {
ui.checkbox(&mut self.avatars, "Load from GitHub, GitLab or Gravatar")
.on_hover_text("On a GitHub repository, its commit list says which account each author is; on GitLab, the host is asked by email. Other authors: an MD5 hash of the email goes to gravatar.com. Cached on disk.");
ui.end_row();
+ ui.label("Code colours");
+ ui.horizontal(|ui| {
+ ui.checkbox(&mut self.vscode_colors, "Use VS Code's colour theme");
+ if self.vscode_colors {
+ let note = match crate::vscode_theme::current() {
+ Some(found) if found.dark == t.dark() => found.name.clone(),
+ Some(found) => format!(
+ "{} is {}: gitcraft's colours meanwhile",
+ found.name,
+ if found.dark { "dark" } else { "light" }
+ ),
+ None => "No VS Code theme found".to_owned(),
+ };
+ ui.label(RichText::new(note).color(t.text_faint).small());
+ }
+ });
+ ui.end_row();
ui.label("Notifications");
ui.checkbox(&mut self.notifications, "When a long operation ends in the background");
ui.end_row();
diff --git a/src/vscode_theme.rs b/src/vscode_theme.rs
new file mode 100644
index 0000000..1746aad
--- /dev/null
+++ b/src/vscode_theme.rs
@@ -0,0 +1,470 @@
+//! The colour theme VS Code is using, read from its settings and extensions and turned into a
+//! syntect theme, so diffs and blame colour code like the editor does.
+
+use std::path::{Path, PathBuf};
+use std::str::FromStr;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::SystemTime;
+
+use serde_json::Value;
+use syntect::highlighting::{
+ Color, ScopeSelectors, StyleModifier, Theme, ThemeItem, ThemeSettings,
+};
+
+/// A VS Code theme ready for syntect.
+pub struct EditorTheme {
+ pub name: String,
+ pub dark: bool,
+ pub theme: Theme,
+}
+
+static ENABLED: AtomicBool = AtomicBool::new(true);
+
+/// Follow VS Code's theme or not (the "Code colours" setting).
+pub fn set_enabled(on: bool) {
+ ENABLED.store(on, Ordering::Relaxed);
+}
+
+pub fn enabled() -> bool {
+ ENABLED.load(Ordering::Relaxed)
+}
+
+/// The theme selected in VS Code; `None` when VS Code isn't installed or its theme can't be
+/// found. Reloaded when VS Code's settings file changes.
+pub fn current() -> Option<Arc<EditorTheme>> {
+ type Cache = Option<(PathBuf, Option<SystemTime>, Option<Arc<EditorTheme>>)>;
+ static CACHE: Mutex<Cache> = Mutex::new(None);
+
+ let editor = installed_editors()
+ .into_iter()
+ .find(|e| e.settings.is_file())?;
+ let modified = std::fs::metadata(&editor.settings)
+ .and_then(|m| m.modified())
+ .ok();
+ let mut cache = CACHE.lock().ok()?;
+ if let Some((path, when, theme)) = cache.as_ref()
+ && *path == editor.settings
+ && *when == modified
+ {
+ return theme.clone();
+ }
+ let theme = load(&editor).map(Arc::new);
+ *cache = Some((editor.settings.clone(), modified, theme.clone()));
+ theme
+}
+
+/// One VS Code flavour: its user settings file and where its extensions live.
+struct Editor {
+ settings: PathBuf,
+ extension_dirs: Vec<PathBuf>,
+}
+
+fn home() -> Option<PathBuf> {
+ std::env::var_os("HOME")
+ .or_else(|| std::env::var_os("USERPROFILE"))
+ .map(PathBuf::from)
+}
+
+fn config_dir() -> Option<PathBuf> {
+ if cfg!(windows) {
+ std::env::var_os("APPDATA").map(PathBuf::from)
+ } else if cfg!(target_os = "macos") {
+ home().map(|h| h.join("Library/Application Support"))
+ } else {
+ std::env::var_os("XDG_CONFIG_HOME")
+ .map(PathBuf::from)
+ .or_else(|| home().map(|h| h.join(".config")))
+ }
+}
+
+/// Folders a VS Code install keeps its built-in extensions in.
+fn builtin_dirs(install: &Path) -> Vec<PathBuf> {
+ let mut dirs = vec![
+ install.join("extensions"),
+ install.join("resources/app/extensions"),
+ ];
+ // Newer Windows installs put each version in a folder of its own.
+ if let Ok(entries) = std::fs::read_dir(install) {
+ for e in entries.flatten() {
+ dirs.push(e.path().join("resources/app/extensions"));
+ }
+ }
+ dirs.into_iter().filter(|d| d.is_dir()).collect()
+}
+
+fn installed_editors() -> Vec<Editor> {
+ let (Some(config), Some(home)) = (config_dir(), home()) else {
+ return Vec::new();
+ };
+ let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from);
+ let program_files = std::env::var_os("ProgramFiles").map(PathBuf::from);
+ // (settings folder, user extensions folder, install folder names)
+ let flavours: [(&str, &str, &[&str]); 3] = [
+ (
+ "Code",
+ ".vscode",
+ &[
+ "Microsoft VS Code",
+ "Visual Studio Code.app/Contents/Resources/app",
+ "code",
+ "visual-studio-code",
+ ],
+ ),
+ (
+ "Code - Insiders",
+ ".vscode-insiders",
+ &[
+ "Microsoft VS Code Insiders",
+ "Visual Studio Code - Insiders.app/Contents/Resources/app",
+ "code-insiders",
+ ],
+ ),
+ (
+ "VSCodium",
+ ".vscode-oss",
+ &[
+ "VSCodium",
+ "VSCodium.app/Contents/Resources/app",
+ "codium",
+ "vscodium",
+ ],
+ ),
+ ];
+ let mut roots: Vec<PathBuf> = Vec::new();
+ if let Some(l) = &local {
+ roots.push(l.join("Programs"));
+ }
+ if let Some(p) = &program_files {
+ roots.push(p.clone());
+ }
+ roots.extend(["/Applications", "/usr/share", "/usr/lib", "/opt"].map(PathBuf::from));
+
+ flavours
+ .iter()
+ .map(|(settings, extensions, installs)| {
+ let mut extension_dirs = vec![home.join(extensions).join("extensions")];
+ for root in &roots {
+ for name in *installs {
+ extension_dirs.extend(builtin_dirs(&root.join(name)));
+ }
+ }
+ Editor {
+ settings: config.join(settings).join("User/settings.json"),
+ extension_dirs,
+ }
+ })
+ .collect()
+}
+
+fn load(editor: &Editor) -> Option<EditorTheme> {
+ let settings = read_jsonc(&editor.settings)?;
+ let name = settings.get("workbench.colorTheme")?.as_str()?.to_owned();
+ let (path, ui_dark) = find_theme(&editor.extension_dirs, &name)?;
+ let (colors, rules, kind) = read_theme(&path, 0)?;
+ let dark = match kind.as_deref() {
+ Some("light" | "hcLight") => false,
+ Some(_) => true,
+ None => ui_dark,
+ };
+ Some(EditorTheme {
+ theme: build(&name, &colors, &rules),
+ name,
+ dark,
+ })
+}
+
+/// Finds the theme file contributed under `name` (its label or id), and whether VS Code
+/// treats it as dark.
+fn find_theme(dirs: &[PathBuf], name: &str) -> Option<(PathBuf, bool)> {
+ for dir in dirs {
+ let Ok(entries) = std::fs::read_dir(dir) else {
+ continue;
+ };
+ // Newest version first when an extension is installed more than once.
+ let mut exts: Vec<PathBuf> = entries.flatten().map(|e| e.path()).collect();
+ exts.sort();
+ exts.reverse();
+ for ext in exts {
+ let Some(pkg) = read_jsonc(&ext.join("package.json")) else {
+ continue;
+ };
+ let Some(themes) = pkg.pointer("/contributes/themes").and_then(Value::as_array) else {
+ continue;
+ };
+ let mut nls = None;
+ for t in themes {
+ let id = t.get("id").and_then(Value::as_str);
+ let mut label = t.get("label").and_then(Value::as_str).map(str::to_owned);
+ if let Some(key) = label
+ .as_deref()
+ .and_then(|l| l.strip_prefix('%'))
+ .and_then(|l| l.strip_suffix('%'))
+ {
+ let nls = nls.get_or_insert_with(|| read_jsonc(&ext.join("package.nls.json")));
+ label = nls
+ .as_ref()
+ .and_then(|n| n.get(key))
+ .and_then(Value::as_str)
+ .map(str::to_owned);
+ }
+ if id != Some(name) && label.as_deref() != Some(name) {
+ continue;
+ }
+ let path = t.get("path").and_then(Value::as_str)?;
+ let ui = t
+ .get("uiTheme")
+ .and_then(Value::as_str)
+ .unwrap_or("vs-dark");
+ return Some((ext.join(path), !matches!(ui, "vs" | "hc-light")));
+ }
+ }
+ }
+ None
+}
+
+/// Workbench colours, token rules and type (`dark`, `light`, ...) of a theme file.
+type ThemeFile = (serde_json::Map<String, Value>, Vec<Value>, Option<String>);
+
+/// Reads a theme file, following its `include`s.
+fn read_theme(path: &Path, depth: u32) -> Option<ThemeFile> {
+ if depth > 8 {
+ return None;
+ }
+ let json = read_jsonc(path)?;
+ let (mut colors, mut rules, mut kind) = match json.get("include").and_then(Value::as_str) {
+ Some(inc) => read_theme(&path.parent()?.join(inc), depth + 1)?,
+ None => Default::default(),
+ };
+ if let Some(c) = json.get("colors").and_then(Value::as_object) {
+ colors.extend(c.clone());
+ }
+ // A theme may point at a .tmTheme file instead; only inline rules are read.
+ if let Some(r) = json.get("tokenColors").and_then(Value::as_array) {
+ rules.extend(r.iter().cloned());
+ }
+ if let Some(t) = json.get("type").and_then(Value::as_str) {
+ kind = Some(t.to_owned());
+ }
+ Some((colors, rules, kind))
+}
+
+fn build(name: &str, colors: &serde_json::Map<String, Value>, rules: &[Value]) -> Theme {
+ let color = |key: &str| {
+ colors
+ .get(key)
+ .and_then(Value::as_str)
+ .and_then(parse_color)
+ };
+ let mut settings = ThemeSettings {
+ foreground: color("editor.foreground"),
+ background: color("editor.background"),
+ ..Default::default()
+ };
+ let mut scopes = Vec::new();
+ for rule in rules {
+ let Some(s) = rule.get("settings") else {
+ continue;
+ };
+ let foreground = s
+ .get("foreground")
+ .and_then(Value::as_str)
+ .and_then(parse_color);
+ let selector = match rule.get("scope") {
+ Some(Value::String(s)) => s.clone(),
+ Some(Value::Array(list)) => list
+ .iter()
+ .filter_map(Value::as_str)
+ .collect::<Vec<_>>()
+ .join(", "),
+ // A rule without a scope sets the defaults.
+ _ => {
+ if settings.foreground.is_none() {
+ settings.foreground = foreground;
+ }
+ continue;
+ }
+ };
+ let Some(foreground) = foreground else {
+ continue;
+ };
+ let Ok(scope) = ScopeSelectors::from_str(selector.trim()) else {
+ continue;
+ };
+ scopes.push(ThemeItem {
+ scope,
+ style: StyleModifier {
+ foreground: Some(foreground),
+ background: None,
+ font_style: None,
+ },
+ });
+ }
+ Theme {
+ name: Some(name.to_owned()),
+ author: None,
+ settings,
+ scopes,
+ }
+}
+
+/// `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`.
+fn parse_color(s: &str) -> Option<Color> {
+ let hex = s.trim().strip_prefix('#')?;
+ let digit =
+ |i: usize, len: usize| u8::from_str_radix(hex.get(i * len..i * len + len)?, 16).ok();
+ let (r, g, b, a) = match hex.len() {
+ 3 | 4 => {
+ let d = |i| digit(i, 1).map(|v| v * 17);
+ (
+ d(0)?,
+ d(1)?,
+ d(2)?,
+ if hex.len() == 4 { d(3)? } else { 255 },
+ )
+ }
+ 6 | 8 => (
+ digit(0, 2)?,
+ digit(1, 2)?,
+ digit(2, 2)?,
+ if hex.len() == 8 { digit(3, 2)? } else { 255 },
+ ),
+ _ => return None,
+ };
+ Some(Color { r, g, b, a })
+}
+
+fn read_jsonc(path: &Path) -> Option<Value> {
+ let text = std::fs::read_to_string(path).ok()?;
+ serde_json::from_str(&strip_jsonc(text.trim_start_matches('\u{feff}'))).ok()
+}
+
+/// Removes the comments and trailing commas VS Code allows in its JSON files.
+fn strip_jsonc(src: &str) -> String {
+ let mut out = String::with_capacity(src.len());
+ let mut chars = src.chars().peekable();
+ let mut in_string = false;
+ while let Some(c) = chars.next() {
+ if in_string {
+ out.push(c);
+ match c {
+ '\\' => out.extend(chars.next()),
+ '"' => in_string = false,
+ _ => {}
+ }
+ continue;
+ }
+ match (c, chars.peek()) {
+ ('"', _) => {
+ in_string = true;
+ out.push(c);
+ }
+ ('/', Some('/')) => {
+ for c in chars.by_ref() {
+ if c == '\n' {
+ out.push('\n');
+ break;
+ }
+ }
+ }
+ ('/', Some('*')) => {
+ chars.next();
+ let mut prev = ' ';
+ for c in chars.by_ref() {
+ if prev == '*' && c == '/' {
+ break;
+ }
+ prev = c;
+ }
+ out.push(' ');
+ }
+ (']' | '}', _) => {
+ // Drop a comma left right before the closing bracket.
+ let kept = out.trim_end().len();
+ if out[..kept].ends_with(',') {
+ out.truncate(kept - 1);
+ }
+ out.push(c);
+ }
+ _ => out.push(c),
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn strips_comments_and_trailing_commas() {
+ let src = r#"{
+ // a comment
+ "a": "http://x", /* block */ "b": [1, 2,],
+ "c": "quote \" // not a comment",
+ }"#;
+ let v: Value = serde_json::from_str(&strip_jsonc(src)).unwrap_or_default();
+ assert_eq!(v["a"], "http://x");
+ assert_eq!(v["b"], serde_json::json!([1, 2]));
+ assert_eq!(v["c"], "quote \" // not a comment");
+ }
+
+ #[test]
+ fn parses_colours() {
+ assert_eq!(
+ parse_color("#fcfcfa"),
+ Some(Color {
+ r: 0xfc,
+ g: 0xfc,
+ b: 0xfa,
+ a: 255
+ })
+ );
+ assert_eq!(
+ parse_color("#f0a8"),
+ Some(Color {
+ r: 255,
+ g: 0,
+ b: 0xaa,
+ a: 0x88
+ })
+ );
+ assert_eq!(parse_color("#12345"), None);
+ assert_eq!(parse_color("red"), None);
+ }
+
+ #[test]
+ fn reads_an_extension_theme_with_include() {
+ let dir = std::env::temp_dir().join(format!("gitcraft-vstheme-{}", std::process::id()));
+ let ext = dir.join("someone.nice-theme-1.0.0");
+ let _ = std::fs::create_dir_all(ext.join("themes"));
+ let write = |p: &str, s: &str| {
+ let _ = std::fs::write(ext.join(p), s);
+ };
+ write(
+ "package.json",
+ r#"{ "contributes": { "themes": [
+ { "label": "%label%", "uiTheme": "vs-dark", "path": "./themes/nice.json" } ] } }"#,
+ );
+ write("package.nls.json", r#"{ "label": "Nice Dark" }"#);
+ write(
+ "themes/base.json",
+ r##"{ "colors": { "editor.foreground": "#aaaaaa" },
+ "tokenColors": [ { "scope": "comment", "settings": { "foreground": "#777777" } } ] }"##,
+ );
+ write(
+ "themes/nice.json",
+ r##"{ "include": "./base.json", // comment
+ "tokenColors": [ { "scope": ["keyword", "storage"], "settings": { "foreground": "#ff6188" } }, ] }"##,
+ );
+ let found = find_theme(std::slice::from_ref(&dir), "Nice Dark");
+ let read = found.as_ref().and_then(|(path, _)| read_theme(path, 0));
+ let _ = std::fs::remove_dir_all(&dir);
+ assert!(found.is_some_and(|(_, dark)| dark));
+ assert!(read.is_some());
+ let (colors, rules, _) = read.unwrap_or_default();
+ let theme = build("Nice Dark", &colors, &rules);
+ assert_eq!(theme.scopes.len(), 2);
+ assert_eq!(theme.settings.foreground, parse_color("#aaaaaa"));
+ }
+}