Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ mmdr-size-api = ["jcode-tui-mermaid/mmdr-size-api"]
pdf = ["dep:jcode-pdf"]

[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_System_Threading"] }
windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Security", "Win32_System_JobObjects", "Win32_System_Threading"] }

[target.'cfg(target_os = "macos")'.dependencies]
global-hotkey = "0.7"
Expand Down
167 changes: 167 additions & 0 deletions crates/jcode-build-support/src/customizations.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
use super::{
SelfDevCustomizationOutcome, SelfDevCustomizationOutcomeStatus, SelfDevCustomizationRecord,
SelfDevCustomizationStatus,
};
use anyhow::Result;
use chrono::Utc;
use jcode_storage as storage;
use std::path::PathBuf;

fn customizations_dir() -> Result<PathBuf> {
let dir = storage::jcode_dir()?.join("selfdev").join("customizations");
storage::ensure_dir(&dir)?;
Ok(dir)
}

pub fn customization_records_dir() -> Result<PathBuf> {
let dir = customizations_dir()?.join("records");
storage::ensure_dir(&dir)?;
Ok(dir)
}

pub fn customization_patches_dir() -> Result<PathBuf> {
let dir = customizations_dir()?.join("patches");
storage::ensure_dir(&dir)?;
Ok(dir)
}

pub fn customization_record_path(id: &str) -> Result<PathBuf> {
Ok(customization_records_dir()?.join(format!("{}.json", sanitize_record_id(id))))
}

pub fn customization_patch_path(id: &str) -> Result<PathBuf> {
Ok(customization_patches_dir()?.join(format!("{}.patch", sanitize_record_id(id))))
}

pub fn sanitize_record_id(id: &str) -> String {
let mut clean = String::with_capacity(id.len());
for ch in id.chars() {
if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_') {
clean.push(ch.to_ascii_lowercase());
} else {
clean.push('-');
}
}
let clean = clean.trim_matches('-');
if clean.is_empty() {
format!("customization-{}", Utc::now().timestamp_millis())
} else {
clean.chars().take(96).collect()
}
}

pub fn create_customization_record(
mut record: SelfDevCustomizationRecord,
patch: Option<&str>,
) -> Result<SelfDevCustomizationRecord> {
record.id = sanitize_record_id(&record.id);
let now = Utc::now();
record.updated_at = now;
if record.created_at > now {
record.created_at = now;
}

let record_path = customization_record_path(&record.id)?;
if record_path.exists() {
anyhow::bail!("customization record `{}` already exists", record.id);
}

if let Some(patch) = patch.filter(|patch| !patch.trim().is_empty()) {
let patch_path = customization_patch_path(&record.id)?;
Comment on lines +57 to +70
if patch_path.exists() {
anyhow::bail!("customization patch `{}` already exists", record.id);
}
storage::write_text_secret(&patch_path, patch)?;
record.provenance.patch_path = Some(patch_path);
}

storage::write_json_secret(&record_path, &record)?;
Ok(record)
}

pub fn save_customization_record(record: &SelfDevCustomizationRecord) -> Result<()> {
storage::write_json_secret(&customization_record_path(&record.id)?, record)
}

pub fn load_customization_record(id: &str) -> Result<Option<SelfDevCustomizationRecord>> {
let path = customization_record_path(id)?;
if path.exists() {
Ok(Some(storage::read_json(&path)?))
} else {
Ok(None)
}
}

pub fn list_customization_records() -> Result<Vec<SelfDevCustomizationRecord>> {
let dir = customization_records_dir()?;
let mut records = Vec::new();
for entry in std::fs::read_dir(dir)? {
let path = entry?.path();
if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
continue;
}
if let Ok(record) = storage::read_json::<SelfDevCustomizationRecord>(&path) {
records.push(record);
}
}
records.sort_by(|a, b| {
b.updated_at
.cmp(&a.updated_at)
.then_with(|| a.id.cmp(&b.id))
});
Ok(records)
}

pub fn list_active_customization_records() -> Result<Vec<SelfDevCustomizationRecord>> {
Ok(list_customization_records()?
.into_iter()
.filter(SelfDevCustomizationRecord::is_active)
.collect())
}

pub fn disable_customization_record(
id: &str,
detail: Option<String>,
) -> Result<SelfDevCustomizationRecord> {
let mut record = load_customization_record(id)?
.ok_or_else(|| anyhow::anyhow!("customization record `{}` not found", id))?;
let now = Utc::now();
record.status = SelfDevCustomizationStatus::Disabled;
record.disabled_at = Some(now);
record.updated_at = now;
record.outcomes.push(SelfDevCustomizationOutcome {
status: SelfDevCustomizationOutcomeStatus::Disabled,
timestamp: now,
detail,
validation_commands: Vec::new(),
});
save_customization_record(&record)?;
Ok(record)
}

pub fn append_customization_outcome(
id: &str,
outcome: SelfDevCustomizationOutcome,
) -> Result<SelfDevCustomizationRecord> {
let mut record = load_customization_record(id)?
.ok_or_else(|| anyhow::anyhow!("customization record `{}` not found", id))?;
record.updated_at = Utc::now();
record.outcomes.push(outcome);
save_customization_record(&record)?;
Ok(record)
}

pub fn summarize_customization_update_state() -> Result<Vec<SelfDevCustomizationOutcome>> {
Ok(list_active_customization_records()?
.into_iter()
.map(|record| SelfDevCustomizationOutcome {
status: SelfDevCustomizationOutcomeStatus::NeedsReview,
timestamp: Utc::now(),
detail: Some(format!(
"Customization `{}` is active and should be reviewed against this update.",
record.id
)),
validation_commands: record.validation.commands,
})
.collect())
}
17 changes: 14 additions & 3 deletions crates/jcode-build-support/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
mod customizations;
mod paths;
mod platform_support;
mod source_state;
mod storage_helpers;

pub use customizations::{
append_customization_outcome, create_customization_record, customization_patch_path,
customization_patches_dir, customization_record_path, customization_records_dir,
disable_customization_record, list_active_customization_records, list_customization_records,
load_customization_record, sanitize_record_id, save_customization_record,
summarize_customization_update_state,
};
pub use paths::{
SELFDEV_CARGO_PROFILE, binary_name, binary_stem, client_update_candidate,
current_binary_build_time_string, current_binary_built_at, find_dev_binary,
Expand All @@ -13,8 +21,9 @@ pub use paths::{
};
pub use source_state::{
current_build_info, current_git_diff, current_git_hash, current_git_hash_full,
current_source_state, ensure_source_state_matches, get_commit_message, is_working_tree_dirty,
repo_build_version, repo_scope_key, worktree_scope_key,
current_git_patch_with_untracked, current_source_state, ensure_source_state_matches,
get_commit_message, is_working_tree_dirty, repo_build_version, repo_scope_key,
worktree_scope_key,
};
pub use storage_helpers::{
build_log_path, build_progress_path, builds_dir, canary_binary_path, clear_build_progress,
Expand All @@ -37,7 +46,9 @@ use std::time::{Duration, Instant};
pub use jcode_selfdev_types::{
BinaryChoice, BinaryVersionReport, BuildInfo, CanaryStatus, CrashInfo, DevBinarySourceMetadata,
MigrationContext, PendingActivation, PublishedBuild, SelfDevBuildCommand, SelfDevBuildTarget,
SourceState,
SelfDevCustomizationBuildMetadata, SelfDevCustomizationOutcome,
SelfDevCustomizationOutcomeStatus, SelfDevCustomizationProvenance, SelfDevCustomizationRecord,
SelfDevCustomizationStatus, SelfDevCustomizationValidation, SourceState,
};

/// Manifest tracking build versions and their status
Expand Down
51 changes: 50 additions & 1 deletion crates/jcode-build-support/src/source_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,13 +184,62 @@ pub fn current_git_hash_full(repo_dir: &Path) -> Result<String> {
/// Get the git diff for uncommitted changes
pub fn current_git_diff(repo_dir: &Path) -> Result<String> {
let output = Command::new("git")
.args(["diff", "HEAD"])
.args(["diff", "--binary", "HEAD"])
.current_dir(repo_dir)
.output()?;

Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

pub fn current_git_patch_with_untracked(repo_dir: &Path) -> Result<String> {
let mut patch = current_git_diff(repo_dir)?;
let untracked = git_output_bytes(
Comment on lines +194 to +196
repo_dir,
&["ls-files", "--others", "--exclude-standard", "-z"],
)?;

for path in untracked
.split(|byte| *byte == 0)
.filter(|entry| !entry.is_empty())
{
let relative = String::from_utf8_lossy(path);
let path = relative.as_ref();
let null_device = if cfg!(windows) { "NUL" } else { "/dev/null" };
let output = Command::new("git")
.args(["diff", "--binary", "--no-index", "--", null_device, path])
.current_dir(repo_dir)
.output()?;

match output.status.code() {
Some(0) | Some(1) => {}
code => {
anyhow::bail!(
"git diff --no-index for untracked file {} failed with status {:?}",
path,
code
);
}
}

if !patch.is_empty() && !patch.ends_with('\n') {
patch.push('\n');
}
patch.push_str(&String::from_utf8_lossy(&output.stdout));
if !output.stderr.is_empty() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
anyhow::bail!(
"git diff --no-index for untracked file {} wrote stderr: {}",
path,
stderr.trim()
);
}
}
}

Ok(patch)
}

/// Check if working tree is dirty
pub fn is_working_tree_dirty(repo_dir: &Path) -> Result<bool> {
let output = Command::new("git")
Expand Down
Loading