repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/memory/general.rs
src-tauri/src/data_harvester/memory/general.rs
use serde::Serialize; cfg_if::cfg_if! { if #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))] { pub mod heim; pub use self::heim::*; } else if #[cfg(target_os = "freebsd")] { pub mod sysinfo; pub use self::sysinfo::*; } } #[derive(Debug, Clone, Default, Serialize)] pub struct MemHarvest { pub mem_total_in_kib: u64, pub mem_used_in_kib: u64, pub use_percent: Option<f64>, } #[derive(Debug)] pub struct MemCollect { pub ram: crate::utils::error::Result<Option<MemHarvest>>, pub swap: crate::utils::error::Result<Option<MemHarvest>>, #[cfg(feature = "zfs")] pub arc: crate::utils::error::Result<Option<MemHarvest>>, #[cfg(feature = "gpu")] pub gpus: crate::utils::error::Result<Option<Vec<(String, MemHarvest)>>>, }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/memory/general/heim.rs
src-tauri/src/data_harvester/memory/general/heim.rs
//! Data collection for memory via heim. use crate::data_harvester::memory::{MemCollect, MemHarvest}; pub async fn get_mem_data() -> MemCollect { MemCollect { ram: get_ram_data().await, swap: get_swap_data().await, #[cfg(feature = "zfs")] arc: get_arc_data().await, #[cfg(feature = "gpu")] gpus: get_gpu_data().await, } } pub async fn get_ram_data() -> crate::utils::error::Result<Option<MemHarvest>> { let (mem_total_in_kib, mem_used_in_kib) = { #[cfg(target_os = "linux")] { // TODO: [OPT] is this efficient? use smol::fs::read_to_string; let meminfo = read_to_string("/proc/meminfo").await?; // All values are in KiB by default. let mut mem_total = 0; let mut cached = 0; let mut s_reclaimable = 0; let mut shmem = 0; let mut buffers = 0; let mut mem_free = 0; let mut keys_read: u8 = 0; const TOTAL_KEYS_NEEDED: u8 = 6; for line in meminfo.lines() { if let Some((label, value)) = line.split_once(':') { let to_write = match label { "MemTotal" => &mut mem_total, "MemFree" => &mut mem_free, "Buffers" => &mut buffers, "Cached" => &mut cached, "Shmem" => &mut shmem, "SReclaimable" => &mut s_reclaimable, _ => { continue; } }; if let Some((number, _unit)) = value.trim_start().split_once(' ') { // Parse the value, remember it's in KiB! if let Ok(number) = number.parse::<u64>() { *to_write = number; // We only need a few keys, so we can bail early. keys_read += 1; if keys_read == TOTAL_KEYS_NEEDED { break; } } } } } // Let's preface this by saying that memory usage calculations are... not straightforward. // There are conflicting implementations everywhere. // // Now that we've added this preface (mainly for future reference), the current implementation below for usage // is based on htop's calculation formula. See // https://github.com/htop-dev/htop/blob/976c6123f41492aaf613b9d172eef1842fb7b0a3/linux/LinuxProcessList.c#L1584 // for implementation details as of writing. // // Another implementation, commonly used in other things, is to skip the shmem part of the calculation, // which matches gopsutil and stuff like free. let total = mem_total; let cached_mem = cached + s_reclaimable - shmem; let used_diff = mem_free + cached_mem + buffers; let used = if total >= used_diff { total - used_diff } else { total - mem_free }; (total, used) } #[cfg(target_os = "macos")] { let memory = heim::memory::memory().await?; use heim::memory::os::macos::MemoryExt; use heim::units::information::kibibyte; ( memory.total().get::<kibibyte>(), memory.active().get::<kibibyte>() + memory.wire().get::<kibibyte>(), ) } #[cfg(target_os = "windows")] { let memory = heim::memory::memory().await?; use heim::units::information::kibibyte; let mem_total_in_kib = memory.total().get::<kibibyte>(); ( mem_total_in_kib, mem_total_in_kib - memory.available().get::<kibibyte>(), ) } #[cfg(target_os = "freebsd")] { let mut s = System::new(); s.refresh_memory(); (s.total_memory(), s.used_memory()) } }; Ok(Some(MemHarvest { mem_total_in_kib, mem_used_in_kib, use_percent: if mem_total_in_kib == 0 { None } else { Some(mem_used_in_kib as f64 / mem_total_in_kib as f64 * 100.0) }, })) } pub async fn get_swap_data() -> crate::utils::error::Result<Option<MemHarvest>> { #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))] let memory = heim::memory::swap().await?; #[cfg(target_os = "freebsd")] let mut memory = System::new(); let (mem_total_in_kib, mem_used_in_kib) = { #[cfg(target_os = "linux")] { // Similar story to above - heim parses this information incorrectly as far as I can tell, so kilobytes = kibibytes here. use heim::units::information::kilobyte; ( memory.total().get::<kilobyte>(), memory.used().get::<kilobyte>(), ) } #[cfg(any(target_os = "windows", target_os = "macos"))] { use heim::units::information::kibibyte; ( memory.total().get::<kibibyte>(), memory.used().get::<kibibyte>(), ) } #[cfg(target_os = "freebsd")] { memory.refresh_memory(); (memory.total_swap(), memory.used_swap()) } }; Ok(Some(MemHarvest { mem_total_in_kib, mem_used_in_kib, use_percent: if mem_total_in_kib == 0 { None } else { Some(mem_used_in_kib as f64 / mem_total_in_kib as f64 * 100.0) }, })) } #[cfg(feature = "zfs")] pub async fn get_arc_data() -> crate::utils::error::Result<Option<MemHarvest>> { let (mem_total_in_kib, mem_used_in_kib) = { #[cfg(target_os = "linux")] { let mut mem_arc = 0; let mut mem_total = 0; let mut zfs_keys_read: u8 = 0; const ZFS_KEYS_NEEDED: u8 = 2; use smol::fs::read_to_string; let arcinfo = read_to_string("/proc/spl/kstat/zfs/arcstats").await?; for line in arcinfo.lines() { if let Some((label, value)) = line.split_once(' ') { let to_write = match label { "size" => &mut mem_arc, "memory_all_bytes" => &mut mem_total, _ => { continue; } }; if let Some((_type, number)) = value.trim_start().rsplit_once(' ') { // Parse the value, remember it's in bytes! if let Ok(number) = number.parse::<u64>() { *to_write = number; // We only need a few keys, so we can bail early. zfs_keys_read += 1; if zfs_keys_read == ZFS_KEYS_NEEDED { break; } } } } } (mem_total / 1024, mem_arc / 1024) } #[cfg(target_os = "freebsd")] { use sysctl::Sysctl; if let (Ok(mem_arc_value), Ok(mem_sys_value)) = ( sysctl::Ctl::new("kstat.zfs.misc.arcstats.size"), sysctl::Ctl::new("hw.physmem"), ) { if let (Ok(sysctl::CtlValue::U64(arc)), Ok(sysctl::CtlValue::Ulong(mem))) = (mem_arc_value.value(), mem_sys_value.value()) { (mem / 1024, arc / 1024) } else { (0, 0) } } else { (0, 0) } } #[cfg(target_os = "macos")] { (0, 0) } #[cfg(target_os = "windows")] { (0, 0) } }; Ok(Some(MemHarvest { mem_total_in_kib, mem_used_in_kib, use_percent: if mem_total_in_kib == 0 { None } else { Some(mem_used_in_kib as f64 / mem_total_in_kib as f64 * 100.0) }, })) } #[cfg(feature = "nvidia")] pub async fn get_gpu_data() -> crate::utils::error::Result<Option<Vec<(String, MemHarvest)>>> { use crate::data_harvester::nvidia::NVML_DATA; if let Ok(nvml) = &*NVML_DATA { if let Ok(ngpu) = nvml.device_count() { let mut results = Vec::with_capacity(ngpu as usize); for i in 0..ngpu { if let Ok(device) = nvml.device_by_index(i) { if let (Ok(name), Ok(mem)) = (device.name(), device.memory_info()) { // add device memory in bytes let mem_total_in_kib = mem.total / 1024; let mem_used_in_kib = mem.used / 1024; results.push(( name, MemHarvest { mem_total_in_kib, mem_used_in_kib, use_percent: if mem_total_in_kib == 0 { None } else { Some(mem_used_in_kib as f64 / mem_total_in_kib as f64 * 100.0) }, }, )); } } } Ok(Some(results)) } else { Ok(None) } } else { Ok(None) } }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/memory/general/sysinfo.rs
src-tauri/src/data_harvester/memory/general/sysinfo.rs
//! Data collection for memory via sysinfo. use sysinfo::{System, SystemExt}; use crate::data_harvester::memory::{MemCollect, MemHarvest}; pub async fn get_mem_data(sys: &System, actually_get: bool, _get_gpu: bool) -> MemCollect { if !actually_get { MemCollect { ram: Ok(None), swap: Ok(None), #[cfg(feature = "zfs")] arc: Ok(None), #[cfg(feature = "gpu")] gpus: Ok(None), } } else { MemCollect { ram: get_ram_data(sys).await, swap: get_swap_data(sys).await, #[cfg(feature = "zfs")] arc: get_arc_data().await, #[cfg(feature = "gpu")] gpus: if _get_gpu { get_gpu_data().await } else { Ok(None) }, } } } pub async fn get_ram_data(sys: &System) -> crate::utils::error::Result<Option<MemHarvest>> { let (mem_total_in_kib, mem_used_in_kib) = (sys.total_memory() / 1024, sys.used_memory() / 1024); Ok(Some(MemHarvest { mem_total_in_kib, mem_used_in_kib, use_percent: if mem_total_in_kib == 0 { None } else { Some(mem_used_in_kib as f64 / mem_total_in_kib as f64 * 100.0) }, })) } pub async fn get_swap_data(sys: &System) -> crate::utils::error::Result<Option<MemHarvest>> { let (mem_total_in_kib, mem_used_in_kib) = (sys.total_swap() / 1024, sys.used_swap() / 1024); Ok(Some(MemHarvest { mem_total_in_kib, mem_used_in_kib, use_percent: if mem_total_in_kib == 0 { None } else { Some(mem_used_in_kib as f64 / mem_total_in_kib as f64 * 100.0) }, })) } #[cfg(feature = "zfs")] pub async fn get_arc_data() -> crate::utils::error::Result<Option<MemHarvest>> { let (mem_total_in_kib, mem_used_in_kib) = { #[cfg(target_os = "freebsd")] { use sysctl::Sysctl; if let (Ok(mem_arc_value), Ok(mem_sys_value)) = ( sysctl::Ctl::new("kstat.zfs.misc.arcstats.size"), sysctl::Ctl::new("hw.physmem"), ) { if let (Ok(sysctl::CtlValue::U64(arc)), Ok(sysctl::CtlValue::Ulong(mem))) = (mem_arc_value.value(), mem_sys_value.value()) { (mem / 1024, arc / 1024) } else { (0, 0) } } else { (0, 0) } } }; Ok(Some(MemHarvest { mem_total_in_kib, mem_used_in_kib, use_percent: if mem_total_in_kib == 0 { None } else { Some(mem_used_in_kib as f64 / mem_total_in_kib as f64 * 100.0) }, })) } #[cfg(feature = "nvidia")] pub async fn get_gpu_data() -> crate::utils::error::Result<Option<Vec<(String, MemHarvest)>>> { use crate::data_harvester::nvidia::NVML_DATA; if let Ok(nvml) = &*NVML_DATA { if let Ok(ngpu) = nvml.device_count() { let mut results = Vec::with_capacity(ngpu as usize); for i in 0..ngpu { if let Ok(device) = nvml.device_by_index(i) { if let (Ok(name), Ok(mem)) = (device.name(), device.memory_info()) { // add device memory in bytes let mem_total_in_kib = mem.total / 1024; let mem_used_in_kib = mem.used / 1024; results.push(( name, MemHarvest { mem_total_in_kib, mem_used_in_kib, use_percent: if mem_total_in_kib == 0 { None } else { Some(mem_used_in_kib as f64 / mem_total_in_kib as f64 * 100.0) }, }, )); } } } Ok(Some(results)) } else { Ok(None) } } else { Ok(None) } }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/disks/freebsd.rs
src-tauri/src/data_harvester/disks/freebsd.rs
//! Disk stats for FreeBSD. use std::io; use serde::Deserialize; use super::{DiskHarvest, IoHarvest}; use crate::app::Filter; use crate::data_harvester::deserialize_xo; #[derive(Deserialize, Debug, Default)] #[serde(rename_all = "kebab-case")] struct StorageSystemInformation { filesystem: Vec<FileSystem>, } #[derive(Deserialize, Debug)] #[serde(rename_all = "kebab-case")] struct FileSystem { name: String, total_blocks: u64, used_blocks: u64, available_blocks: u64, mounted_on: String, } pub async fn get_io_usage(actually_get: bool) -> crate::utils::error::Result<Option<IoHarvest>> { if !actually_get { return Ok(None); } let io_harvest = get_disk_info().map(|storage_system_information| { storage_system_information .filesystem .into_iter() .map(|disk| (disk.name, None)) .collect() })?; Ok(Some(io_harvest)) } pub async fn get_disk_usage( actually_get: bool, disk_filter: &Option<Filter>, mount_filter: &Option<Filter>, ) -> crate::utils::error::Result<Option<Vec<DiskHarvest>>> { if !actually_get { return Ok(None); } let vec_disks: Vec<DiskHarvest> = get_disk_info().map(|storage_system_information| { storage_system_information .filesystem .into_iter() .filter_map(|disk| { // Precedence ordering in the case where name and mount filters disagree, "allow" // takes precedence over "deny". // // For implementation, we do this as follows: // // 1. Is the entry allowed through any filter? That is, does it match an entry in a // filter where `is_list_ignored` is `false`? If so, we always keep this entry. // 2. Is the entry denied through any filter? That is, does it match an entry in a // filter where `is_list_ignored` is `true`? If so, we always deny this entry. // 3. Anything else is allowed. let filter_check_map = [(disk_filter, &disk.name), (mount_filter, &disk.mounted_on)]; if matches_allow_list(filter_check_map.as_slice()) || !matches_ignore_list(filter_check_map.as_slice()) { Some(DiskHarvest { free_space: Some(disk.available_blocks * 1024), used_space: Some(disk.used_blocks * 1024), total_space: Some(disk.total_blocks * 1024), mount_point: disk.mounted_on, name: disk.name, }) } else { None } }) .collect() })?; Ok(Some(vec_disks)) } fn matches_allow_list(filter_check_map: &[(&Option<Filter>, &String)]) -> bool { filter_check_map.iter().any(|(filter, text)| match filter { Some(f) if !f.is_list_ignored => f.list.iter().any(|r| r.is_match(text)), Some(_) | None => false, }) } fn matches_ignore_list(filter_check_map: &[(&Option<Filter>, &String)]) -> bool { filter_check_map.iter().any(|(filter, text)| match filter { Some(f) if f.is_list_ignored => f.list.iter().any(|r| r.is_match(text)), Some(_) | None => false, }) } fn get_disk_info() -> io::Result<StorageSystemInformation> { let output = std::process::Command::new("df") .args(["--libxo", "json", "-k", "-t", "ufs,msdosfs,zfs"]) .output()?; deserialize_xo("storage-system-information", &output.stdout) }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/disks/heim.rs
src-tauri/src/data_harvester/disks/heim.rs
//! Disk stats through heim. //! Supports macOS, Linux, and Windows. use crate::data_harvester::disks::{DiskHarvest, IoData, IoHarvest}; cfg_if::cfg_if! { if #[cfg(target_os = "linux")] { pub mod linux; pub use linux::*; } else if #[cfg(any(target_os = "macos", target_os = "windows"))] { pub mod windows_macos; pub use windows_macos::*; } } pub async fn get_io_usage() -> crate::utils::error::Result<Option<IoHarvest>> { use futures::StreamExt; let mut io_hash: std::collections::HashMap<String, Option<IoData>> = std::collections::HashMap::new(); let counter_stream = heim::disk::io_counters().await?; futures::pin_mut!(counter_stream); while let Some(io) = counter_stream.next().await { if let Ok(io) = io { let mount_point = io.device_name().to_str().unwrap_or("Name Unavailable"); io_hash.insert( mount_point.to_string(), Some(IoData { read_bytes: io.read_bytes().get::<heim::units::information::byte>(), write_bytes: io.write_bytes().get::<heim::units::information::byte>(), }), ); } } Ok(Some(io_hash)) } pub async fn get_disk_usage() -> crate::utils::error::Result<Option<Vec<DiskHarvest>>> { use futures::StreamExt; let mut vec_disks: Vec<DiskHarvest> = Vec::new(); let partitions_stream = heim::disk::partitions_physical().await?; futures::pin_mut!(partitions_stream); while let Some(part) = partitions_stream.next().await { if let Ok(partition) = part { let name = get_device_name(&partition); let mount_point = (partition .mount_point() .to_str() .unwrap_or("Name Unavailable")) .to_string(); // The usage line can fail in some cases (for example, if you use Void Linux + LUKS, // see https://github.com/ClementTsang/bottom/issues/419 for details). As such, check // it like this instead. if let Ok(usage) = heim::disk::usage(partition.mount_point()).await { vec_disks.push(DiskHarvest { free_space: Some(usage.free().get::<heim::units::information::byte>()), used_space: Some(usage.used().get::<heim::units::information::byte>()), total_space: Some(usage.total().get::<heim::units::information::byte>()), mount_point, name, }); } else { vec_disks.push(DiskHarvest { free_space: None, used_space: None, total_space: None, mount_point, name, }); } } } Ok(Some(vec_disks)) }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/disks/heim/windows_macos.rs
src-tauri/src/data_harvester/disks/heim/windows_macos.rs
//! macOS and Windows-specific things for Heim disk data collection. use heim::disk::Partition; pub fn get_device_name(partition: &Partition) -> String { if let Some(device) = partition.device() { device .to_os_string() .into_string() .unwrap_or_else(|_| "Name Unavailable".to_string()) } else { "Name Unavailable".to_string() } }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/disks/heim/linux.rs
src-tauri/src/data_harvester/disks/heim/linux.rs
//! Linux-specific things for Heim disk data collection. use heim::disk::Partition; pub fn get_device_name(partition: &Partition) -> String { if let Some(device) = partition.device() { // See if this disk is actually mounted elsewhere on Linux... // This is a workaround to properly map I/O in some cases (i.e. disk encryption), see // https://github.com/ClementTsang/bottom/issues/419 if let Ok(path) = std::fs::read_link(device) { if path.is_absolute() { path.into_os_string() } else { let mut combined_path = std::path::PathBuf::new(); combined_path.push(device); combined_path.pop(); // Pop the current file... combined_path.push(path); if let Ok(canon_path) = std::fs::canonicalize(combined_path) { // Resolve the local path into an absolute one... canon_path.into_os_string() } else { device.to_os_string() } } } else { device.to_os_string() } .into_string() .unwrap_or_else(|_| "Name Unavailable".to_string()) } else { "Name Unavailable".to_string() } }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/network/heim.rs
src-tauri/src/data_harvester/network/heim.rs
//! Gets network data via heim. use std::time::Instant; use super::NetworkHarvest; // TODO: Eventually make it so that this thing also takes individual usage into account, so we can show per-interface! pub async fn get_network_data( prev_net_access_time: Instant, prev_net_rx: &mut u64, prev_net_tx: &mut u64, curr_time: Instant, ) -> crate::utils::error::Result<Option<NetworkHarvest>> { use futures::StreamExt; let io_data = heim::net::io_counters().await?; futures::pin_mut!(io_data); let mut total_rx: u64 = 0; let mut total_tx: u64 = 0; while let Some(io) = io_data.next().await { if let Ok(io) = io { // TODO: Use bytes as the default instead, perhaps? // Since you might have to do a double conversion (bytes -> bits -> bytes) in some cases; // but if you stick to bytes, then in the bytes, case, you do no conversion, and in the bits case, // you only do one conversion... total_rx += io.bytes_recv().get::<heim::units::information::bit>(); total_tx += io.bytes_sent().get::<heim::units::information::bit>(); } } let elapsed_time = curr_time.duration_since(prev_net_access_time).as_secs_f64(); let (rx, tx) = if elapsed_time == 0.0 { (0, 0) } else { ( ((total_rx.saturating_sub(*prev_net_rx)) as f64 / elapsed_time) as u64, ((total_tx.saturating_sub(*prev_net_tx)) as f64 / elapsed_time) as u64, ) }; *prev_net_rx = total_rx; *prev_net_tx = total_tx; Ok(Some(NetworkHarvest { rx, tx, total_rx, total_tx, })) }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/network/sysinfo.rs
src-tauri/src/data_harvester/network/sysinfo.rs
//! Gets network data via sysinfo. use std::time::Instant; use super::NetworkHarvest; pub async fn get_network_data( sys: &sysinfo::System, prev_net_access_time: Instant, prev_net_rx: &mut u64, prev_net_tx: &mut u64, curr_time: Instant, ) -> crate::utils::error::Result<Option<NetworkHarvest>> { use sysinfo::{NetworkExt, SystemExt}; let mut total_rx: u64 = 0; let mut total_tx: u64 = 0; let networks = sys.networks(); for (name, network) in networks { total_rx += network.total_received() * 8; total_tx += network.total_transmitted() * 8; } let elapsed_time = curr_time.duration_since(prev_net_access_time).as_secs_f64(); let (rx, tx) = if elapsed_time == 0.0 { (0, 0) } else { ( ((total_rx.saturating_sub(*prev_net_rx)) as f64 / elapsed_time) as u64, ((total_tx.saturating_sub(*prev_net_tx)) as f64 / elapsed_time) as u64, ) }; *prev_net_rx = total_rx; *prev_net_tx = total_tx; Ok(Some(NetworkHarvest { rx, tx, total_rx, total_tx, })) }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/temperature/linux.rs
src-tauri/src/data_harvester/temperature/linux.rs
//! Gets temperature sensor data for Linux platforms. use std::{fs, path::Path}; use anyhow::{anyhow, Result}; use super::TempHarvest; /// Get temperature sensors from the linux sysfs interface `/sys/class/hwmon`. /// See [here](https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-hwmon) for /// details. /// /// This method will return `0` as the temperature for devices, such as GPUs, /// that support power management features and power themselves off. /// /// Specifically, in laptops with iGPUs and dGPUs, if the dGPU is capable of /// entering ACPI D3cold, reading the temperature sensors will wake it, /// and keep it awake, wasting power. /// /// For such devices, this method will only query the sensors *only* if /// the device is already in ACPI D0. This has the notable issue that /// once this happens, the device will be *kept* on through the sensor /// reading, and not be able to re-enter ACPI D3cold. fn get_from_hwmon() -> Result<Vec<TempHarvest>> { let mut temperature_vec: Vec<TempHarvest> = vec![]; let path = Path::new("/sys/class/hwmon"); // NOTE: Technically none of this is async, *but* sysfs is in memory, // so in theory none of this should block if we're slightly careful. // Of note is that reading the temperature sensors of a device that has // `/sys/class/hwmon/hwmon*/device/power_state` == `D3cold` will // wake the device up, and will block until it initializes. // // Reading the `hwmon*/device/power_state` or `hwmon*/temp*_label` properties // will not wake the device, and thus not block, // and meaning no sensors have to be hidden depending on `power_state` // // It would probably be more ideal to use a proper async runtime.. for entry in path.read_dir()? { let file = entry?; let mut file_path = file.path(); // hwmon includes many sensors, we only want ones with at least one temperature sensor // Reading this file will wake the device, but we're only checking existence. if !file_path.join("temp1_input").exists() { // Note we also check for a `device` subdirectory (e.g. `/sys/class/hwmon/hwmon*/device/`). // This is needed for CentOS, which adds this extra `/device` directory. See: // - https://github.com/nicolargo/glances/issues/1060 // - https://github.com/giampaolo/psutil/issues/971 // - https://github.com/giampaolo/psutil/blob/642438375e685403b4cd60b0c0e25b80dd5a813d/psutil/_pslinux.py#L1316 // // If it does match, then add the `device/` directory to the path. if file_path.join("device/temp1_input").exists() { file_path.push("device"); } else { continue; } } let hwmon_name = file_path.join("name"); let hwmon_name = Some(fs::read_to_string(hwmon_name)?); // Whether the temperature should *actually* be read during enumeration // Set to false if the device is in ACPI D3cold. let should_read_temp = { // Documented at https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-devices-power_state let device = file_path.join("device"); let power_state = device.join("power_state"); if power_state.exists() { let state = fs::read_to_string(power_state)?; let state = state.trim(); // The zenpower3 kernel module (incorrectly?) reports "unknown" // causing this check to fail and temperatures to appear as zero // instead of having the file not exist.. // their self-hosted git instance has disabled sign up, // so this bug cant be reported either. state == "D0" || state == "unknown" } else { true } }; // Enumerate the devices temperature sensors for entry in file_path.read_dir()? { let file = entry?; let name = file.file_name(); // This should always be ASCII let name = name .to_str() .ok_or_else(|| anyhow!("temperature device filenames should be ASCII"))?; // We only want temperature sensors, skip others early if !(name.starts_with("temp") && name.ends_with("input")) { continue; } let temp = file.path(); let temp_label = file_path.join(name.replace("input", "label")); let temp_label = fs::read_to_string(temp_label).ok(); // Do some messing around to get a more sensible name for sensors // // - For GPUs, this will use the kernel device name, ex `card0` // - For nvme drives, this will also use the kernel name, ex `nvme0`. // This is found differently than for GPUs // - For whatever acpitz is, on my machine this is now `thermal_zone0`. // - For k10temp, this will still be k10temp, but it has to be handled special. let human_hwmon_name = { let device = file_path.join("device"); // This will exist for GPUs but not others, this is how // we find their kernel name let drm = device.join("drm"); if drm.exists() { // This should never actually be empty let mut gpu = None; for card in drm.read_dir()? { let card = card?; let name = card.file_name().to_str().unwrap_or_default().to_owned(); if name.starts_with("card") { if let Some(hwmon_name) = hwmon_name.as_ref() { gpu = Some(format!("{} ({})", name, hwmon_name.trim())); } else { gpu = Some(name) } break; } } gpu } else { // This little mess is to account for stuff like k10temp // This is needed because the `device` symlink // points to `nvme*` for nvme drives, but to PCI buses for anything else // If the first character is alphabetic, // its an actual name like k10temp or nvme0, not a PCI bus let link = fs::read_link(device)? .file_name() .map(|f| f.to_str().unwrap_or_default().to_owned()) .unwrap(); if link.as_bytes()[0].is_ascii_alphabetic() { if let Some(hwmon_name) = hwmon_name.as_ref() { Some(format!("{} ({})", link, hwmon_name.trim())) } else { Some(link) } } else { hwmon_name.clone() } } }; let name = match (&human_hwmon_name, &temp_label) { (Some(name), Some(label)) => format!("{}: {}", name.trim(), label.trim()), (None, Some(label)) => label.to_string(), (Some(name), None) => name.to_string(), (None, None) => String::default(), }; let temp = if should_read_temp { if let Ok(temp) = fs::read_to_string(temp) { let temp = temp.trim_end().parse::<f32>().map_err(|e| { crate::utils::error::ToeError::ConversionError(e.to_string()) })?; temp / 1_000.0 } else { // For some devices (e.g. iwlwifi), this file becomes empty when the device // is disabled. In this case we skip the device. continue; } } else { 0.0 }; temperature_vec.push(TempHarvest { name, temperature: temp, }); } } Ok(temperature_vec) } /// Gets data from `/sys/class/thermal/thermal_zone*`. This should only be used if /// [`get_from_hwmon`] doesn't return anything. See /// [here](https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-thermal) for details. fn get_from_thermal_zone() -> Result<Vec<TempHarvest>> { let mut temperatures = vec![]; let path = Path::new("/sys/class/thermal"); for entry in path.read_dir()? { let file = entry?; if file .file_name() .to_string_lossy() .starts_with("thermal_zone") { let file_path = file.path(); let name_path = file_path.join("type"); let name = fs::read_to_string(name_path)?.trim_end().to_string(); let temp_path = file_path.join("temp"); let temp = fs::read_to_string(temp_path)? .trim_end() .parse::<f32>() .map_err(|e| crate::utils::error::ToeError::ConversionError(e.to_string()))? / 1_000.0; temperatures.push(TempHarvest { name, temperature: temp, }); } } Ok(temperatures) } /// Gets temperature sensors and data. pub fn get_temperature_data() -> Result<Option<Vec<TempHarvest>>> { let mut temperature_vec: Vec<TempHarvest> = get_from_hwmon()?; if temperature_vec.is_empty() { // If it's empty, fall back to checking `thermal_zone*`. temperature_vec = get_from_thermal_zone()?; } #[cfg(feature = "nvidia")] { super::nvidia::add_nvidia_data(&mut temperature_vec)?; } Ok(Some(temperature_vec)) }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/temperature/nvidia.rs
src-tauri/src/data_harvester/temperature/nvidia.rs
use nvml_wrapper::enum_wrappers::device::TemperatureSensor; use super::TempHarvest; use crate::data_harvester::nvidia::NVML_DATA; pub fn add_nvidia_data( temperature_vec: &mut Vec<TempHarvest>, temp_type: &TemperatureType, ) -> crate::utils::error::Result<()> { if let Ok(nvml) = &*NVML_DATA { if let Ok(ngpu) = nvml.device_count() { for i in 0..ngpu { if let Ok(device) = nvml.device_by_index(i) { if let (Ok(name), Ok(temperature)) = (device.name(), device.temperature(TemperatureSensor::Gpu)) { let temperature = temperature as f32; temperature_vec.push(TempHarvest { name, temperature }); } } } } } Ok(()) }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/temperature/sysinfo.rs
src-tauri/src/data_harvester/temperature/sysinfo.rs
//! Gets temperature data via sysinfo. use anyhow::Result; use super::TempHarvest; pub fn get_temperature_data(sys: &sysinfo::System) -> Result<Option<Vec<TempHarvest>>> { use sysinfo::{ComponentExt, SystemExt}; let mut temperature_vec: Vec<TempHarvest> = Vec::new(); let sensor_data = sys.components(); for component in sensor_data { let name = component.label().to_string(); temperature_vec.push(TempHarvest { name, temperature: component.temperature(), }); } #[cfg(feature = "nvidia")] { super::nvidia::add_nvidia_data(&mut temperature_vec, temp_type, filter)?; } Ok(Some(temperature_vec)) }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/processes/unix.rs
src-tauri/src/data_harvester/processes/unix.rs
//! Unix-specific parts of process collection. use fxhash::FxHashMap; use crate::utils::error; #[derive(Debug, Default)] pub struct UserTable { pub uid_user_mapping: FxHashMap<libc::uid_t, String>, } impl UserTable { pub fn get_uid_to_username_mapping(&mut self, uid: libc::uid_t) -> error::Result<String> { if let Some(user) = self.uid_user_mapping.get(&uid) { Ok(user.clone()) } else { // SAFETY: getpwuid returns a null pointer if no passwd entry is found for the uid let passwd = unsafe { libc::getpwuid(uid) }; if passwd.is_null() { return Err(error::ToeError::QueryError("Missing passwd".into())); } let username = unsafe { std::ffi::CStr::from_ptr((*passwd).pw_name) } .to_str()? .to_string(); self.uid_user_mapping.insert(uid, username.clone()); Ok(username) } } }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/processes/macos_freebsd.rs
src-tauri/src/data_harvester/processes/macos_freebsd.rs
//! Shared process data harvesting code from macOS and FreeBSD via sysinfo. use std::collections::HashMap; use std::io; use sysinfo::{CpuExt, PidExt, ProcessExt, ProcessStatus, System, SystemExt}; use super::ProcessHarvest; use crate::{data_harvester::processes::UserTable, utils::error::Result, Pid}; pub fn get_process_data<F>( sys: &System, use_current_cpu_total: bool, unnormalized_cpu: bool, mem_total_kb: u64, user_table: &mut UserTable, backup_cpu_proc_usage: F, ) -> Result<Vec<ProcessHarvest>> where F: Fn(&[Pid]) -> io::Result<HashMap<Pid, f64>>, { let mut process_vector: Vec<ProcessHarvest> = Vec::new(); let process_hashmap = sys.processes(); let cpu_usage = sys.global_cpu_info().cpu_usage() as f64 / 100.0; let num_processors = sys.cpus().len() as f64; for process_val in process_hashmap.values() { let name = if process_val.name().is_empty() { let process_cmd = process_val.cmd(); if process_cmd.len() > 1 { process_cmd[0].clone() } else { let process_exe = process_val.exe().file_stem(); if let Some(exe) = process_exe { let process_exe_opt = exe.to_str(); if let Some(exe_name) = process_exe_opt { exe_name.to_string() } else { "".to_string() } } else { "".to_string() } } } else { process_val.name().to_string() }; let command = { let command = process_val.cmd().join(" "); if command.is_empty() { name.to_string() } else { command } }; let pcu = { let usage = process_val.cpu_usage() as f64; if unnormalized_cpu || num_processors == 0.0 { usage } else { usage / num_processors } }; let process_cpu_usage = if use_current_cpu_total && cpu_usage > 0.0 { pcu / cpu_usage } else { pcu }; let disk_usage = process_val.disk_usage(); let process_state = { let ps = process_val.status(); (ps.to_string(), convert_process_status_to_char(ps)) }; let uid = process_val.user_id().map(|u| **u); let pid = process_val.pid().as_u32() as Pid; process_vector.push(ProcessHarvest { pid, parent_pid: { #[cfg(target_os = "macos")] { process_val .parent() .map(|p| p.as_u32() as _) .or_else(|| super::fallback_macos_ppid(pid)) } #[cfg(not(target_os = "macos"))] { process_val.parent().map(|p| p.as_u32() as _) } }, name, command, mem_usage_percent: if mem_total_kb > 0 { process_val.memory() as f64 * 100.0 / mem_total_kb as f64 } else { 0.0 }, mem_usage_bytes: process_val.memory(), cpu_usage_percent: process_cpu_usage, read_bytes_per_sec: disk_usage.read_bytes, write_bytes_per_sec: disk_usage.written_bytes, total_read_bytes: disk_usage.total_read_bytes, total_write_bytes: disk_usage.total_written_bytes, process_state, uid, user: uid .and_then(|uid| { user_table .get_uid_to_username_mapping(uid) .map(Into::into) .ok() }) .unwrap_or_else(|| "N/A".into()), }); } let unknown_state = ProcessStatus::Unknown(0).to_string(); let cpu_usage_unknown_pids: Vec<Pid> = process_vector .iter() .filter(|process| process.process_state.0 == unknown_state) .map(|process| process.pid) .collect(); let cpu_usages = backup_cpu_proc_usage(&cpu_usage_unknown_pids)?; for process in &mut process_vector { if cpu_usages.contains_key(&process.pid) { process.cpu_usage_percent = if unnormalized_cpu || num_processors == 0.0 { *cpu_usages.get(&process.pid).unwrap() } else { *cpu_usages.get(&process.pid).unwrap() / num_processors }; } } Ok(process_vector) } fn convert_process_status_to_char(status: ProcessStatus) -> char { match status { ProcessStatus::Run => 'R', ProcessStatus::Sleep => 'S', ProcessStatus::Idle => 'D', ProcessStatus::Zombie => 'Z', _ => '?', } }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/processes/macos.rs
src-tauri/src/data_harvester/processes/macos.rs
//! Process data collection for macOS. Uses sysinfo and custom bindings. use sysinfo::System; use super::ProcessHarvest; use crate::{data_harvester::processes::UserTable, Pid}; mod sysctl_bindings; pub fn get_process_data( sys: &System, use_current_cpu_total: bool, unnormalized_cpu: bool, mem_total_kb: u64, user_table: &mut UserTable, ) -> crate::utils::error::Result<Vec<ProcessHarvest>> { super::macos_freebsd::get_process_data( sys, use_current_cpu_total, unnormalized_cpu, mem_total_kb, user_table, get_macos_process_cpu_usage, ) } pub(crate) fn fallback_macos_ppid(pid: Pid) -> Option<Pid> { sysctl_bindings::kinfo_process(pid) .map(|kinfo| kinfo.kp_eproc.e_ppid) .ok() } fn get_macos_process_cpu_usage( pids: &[Pid], ) -> std::io::Result<std::collections::HashMap<i32, f64>> { use itertools::Itertools; let output = std::process::Command::new("ps") .args(["-o", "pid=,pcpu=", "-p"]) .arg( // Has to look like this since otherwise, it you hit a `unstable_name_collisions` warning. Itertools::intersperse(pids.iter().map(i32::to_string), ",".to_string()) .collect::<String>(), ) .output()?; let mut result = std::collections::HashMap::new(); String::from_utf8_lossy(&output.stdout) .split_whitespace() .chunks(2) .into_iter() .for_each(|chunk| { let chunk: Vec<&str> = chunk.collect(); if chunk.len() != 2 { panic!("Unexpected `ps` output"); } let pid = chunk[0].parse(); let usage = chunk[1].parse(); if let (Ok(pid), Ok(usage)) = (pid, usage) { result.insert(pid, usage); } }); Ok(result) }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/processes/linux.rs
src-tauri/src/data_harvester/processes/linux.rs
//! Process data collection for Linux. use std::fs::File; use std::io::{BufRead, BufReader}; use fxhash::{FxHashMap, FxHashSet}; use procfs::process::{Process, Stat}; use sysinfo::ProcessStatus; use super::{ProcessHarvest, UserTable}; use crate::data_harvester::cpu::Point; use crate::utils::error::{self, ToeError}; use crate::Pid; /// Maximum character length of a /proc/<PID>/stat process name. /// If it's equal or greater, then we instead refer to the command for the name. const MAX_STAT_NAME_LEN: usize = 15; #[derive(Debug, Clone, Default)] pub struct PrevProcDetails { total_read_bytes: u64, total_write_bytes: u64, cpu_time: u64, } fn calculate_idle_values(line: &str) -> Point { /// Converts a `Option<&str>` value to an f64. If it fails to parse or is `None`, then it will return `0_f64`. fn str_to_f64(val: Option<&str>) -> f64 { val.and_then(|v| v.parse::<f64>().ok()).unwrap_or(0_f64) } let mut val = line.split_whitespace(); let user = str_to_f64(val.next()); let nice: f64 = str_to_f64(val.next()); let system: f64 = str_to_f64(val.next()); let idle: f64 = str_to_f64(val.next()); let iowait: f64 = str_to_f64(val.next()); let irq: f64 = str_to_f64(val.next()); let softirq: f64 = str_to_f64(val.next()); let steal: f64 = str_to_f64(val.next()); // Note we do not get guest/guest_nice, as they are calculated as part of user/nice respectively // See https://github.com/htop-dev/htop/blob/main/linux/LinuxProcessList.c let idle = idle + iowait; let non_idle = user + nice + system + irq + softirq + steal; (idle, non_idle) } struct CpuUsage { /// Difference between the total delta and the idle delta. cpu_usage: f64, /// Overall CPU usage as a fraction. cpu_fraction: f64, } fn cpu_usage_calculation(prev_idle: &mut f64, prev_non_idle: &mut f64) -> error::Result<CpuUsage> { let (idle, non_idle) = { // From SO answer: https://stackoverflow.com/a/23376195 let mut reader = BufReader::new(File::open("/proc/stat")?); let mut first_line = String::new(); reader.read_line(&mut first_line)?; calculate_idle_values(&first_line) }; let total = idle + non_idle; let prev_total = *prev_idle + *prev_non_idle; let total_delta = total - prev_total; let idle_delta = idle - *prev_idle; *prev_idle = idle; *prev_non_idle = non_idle; // TODO: Should these return errors instead? let cpu_usage = if total_delta - idle_delta != 0.0 { total_delta - idle_delta } else { 1.0 }; let cpu_fraction = if total_delta != 0.0 { cpu_usage / total_delta } else { 0.0 }; Ok(CpuUsage { cpu_usage, cpu_fraction, }) } /// Returns the usage and a new set of process times. /// /// NB: cpu_fraction should be represented WITHOUT the x100 factor! fn get_linux_cpu_usage( stat: &Stat, cpu_usage: f64, cpu_fraction: f64, prev_proc_times: u64, use_current_cpu_total: bool, ) -> (f64, u64) { // Based heavily on https://stackoverflow.com/a/23376195 and https://stackoverflow.com/a/1424556 let new_proc_times = stat.utime + stat.stime; let diff = (new_proc_times - prev_proc_times) as f64; // No try_from for u64 -> f64... oh well. if cpu_usage == 0.0 { (0.0, new_proc_times) } else if use_current_cpu_total { ((diff / cpu_usage) * 100.0, new_proc_times) } else { ((diff / cpu_usage) * 100.0 * cpu_fraction, new_proc_times) } } fn read_proc( prev_proc: &PrevProcDetails, process: &Process, cpu_usage: f64, cpu_fraction: f64, use_current_cpu_total: bool, time_difference_in_secs: u64, mem_total_kb: u64, user_table: &mut UserTable, ) -> error::Result<(ProcessHarvest, u64)> { let stat = process.stat()?; let (command, name) = { let truncated_name = stat.comm.as_str(); if let Ok(cmdline) = process.cmdline() { if cmdline.is_empty() { (format!("[{}]", truncated_name), truncated_name.to_string()) } else { ( cmdline.join(" "), if truncated_name.len() >= MAX_STAT_NAME_LEN { if let Some(first_part) = cmdline.first() { // We're only interested in the executable part... not the file path. // That's for command. first_part .rsplit_once('/') .map(|(_prefix, suffix)| suffix) .unwrap_or(truncated_name) .to_string() } else { truncated_name.to_string() } } else { truncated_name.to_string() }, ) } } else { (truncated_name.to_string(), truncated_name.to_string()) } }; let process_state_char = stat.state; let process_state = ( ProcessStatus::from(process_state_char).to_string(), process_state_char, ); let (cpu_usage_percent, new_process_times) = get_linux_cpu_usage( &stat, cpu_usage, cpu_fraction, prev_proc.cpu_time, use_current_cpu_total, ); let parent_pid = Some(stat.ppid); let mem_usage_bytes = stat.rss_bytes()?; let mem_usage_kb = mem_usage_bytes / 1024; let mem_usage_percent = mem_usage_kb as f64 / mem_total_kb as f64 * 100.0; // This can fail if permission is denied! let (total_read_bytes, total_write_bytes, read_bytes_per_sec, write_bytes_per_sec) = if let Ok(io) = process.io() { let total_read_bytes = io.read_bytes; let total_write_bytes = io.write_bytes; let prev_total_read_bytes = prev_proc.total_read_bytes; let prev_total_write_bytes = prev_proc.total_write_bytes; let read_bytes_per_sec = total_read_bytes .saturating_sub(prev_total_read_bytes) .checked_div(time_difference_in_secs) .unwrap_or(0); let write_bytes_per_sec = total_write_bytes .saturating_sub(prev_total_write_bytes) .checked_div(time_difference_in_secs) .unwrap_or(0); ( total_read_bytes, total_write_bytes, read_bytes_per_sec, write_bytes_per_sec, ) } else { (0, 0, 0, 0) }; let uid = process.uid()?; Ok(( ProcessHarvest { pid: process.pid, parent_pid, cpu_usage_percent, mem_usage_percent, mem_usage_bytes, name, command, read_bytes_per_sec, write_bytes_per_sec, total_read_bytes, total_write_bytes, process_state, uid: Some(uid), user: user_table .get_uid_to_username_mapping(uid) .map(Into::into) .unwrap_or_else(|_| "N/A".into()), }, new_process_times, )) } /// How to calculate CPU usage. pub enum CpuUsageStrategy { /// Normalized means the displayed usage percentage is divided over the number of CPU cores. /// /// For example, if the "overall" usage over the entire system is 105%, and there are 5 cores, then /// the displayed percentage is 21%. Normalized, /// Non-normalized means that the overall usage over the entire system is shown, without dividing /// over the number of cores. NonNormalized(f64), } pub fn get_process_data( prev_idle: &mut f64, prev_non_idle: &mut f64, pid_mapping: &mut FxHashMap<Pid, PrevProcDetails>, use_current_cpu_total: bool, normalization: CpuUsageStrategy, time_difference_in_secs: u64, mem_total_kb: u64, user_table: &mut UserTable, ) -> crate::utils::error::Result<Vec<ProcessHarvest>> { // TODO: [PROC THREADS] Add threads if let Ok(CpuUsage { mut cpu_usage, cpu_fraction, }) = cpu_usage_calculation(prev_idle, prev_non_idle) { if let CpuUsageStrategy::NonNormalized(num_cores) = normalization { // Note we *divide* here because the later calculation divides `cpu_usage` - in effect, // multiplying over the number of cores. cpu_usage /= num_cores; } let mut pids_to_clear: FxHashSet<Pid> = pid_mapping.keys().cloned().collect(); let process_vector: Vec<ProcessHarvest> = std::fs::read_dir("/proc")? .filter_map(|dir| { if let Ok(dir) = dir { if let Ok(pid) = dir.file_name().to_string_lossy().trim().parse::<Pid>() { let Ok(process) = Process::new(pid) else { return None; }; let prev_proc_details = pid_mapping.entry(pid).or_default(); if let Ok((process_harvest, new_process_times)) = read_proc( prev_proc_details, &process, cpu_usage, cpu_fraction, use_current_cpu_total, time_difference_in_secs, mem_total_kb, user_table, ) { prev_proc_details.cpu_time = new_process_times; prev_proc_details.total_read_bytes = process_harvest.total_read_bytes; prev_proc_details.total_write_bytes = process_harvest.total_write_bytes; pids_to_clear.remove(&pid); return Some(process_harvest); } } } None }) .collect(); pids_to_clear.iter().for_each(|pid| { pid_mapping.remove(pid); }); Ok(process_vector) } else { Err(ToeError::GenericError( "Could not calculate CPU usage.".to_string(), )) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_proc_cpu_parse() { assert_eq!( (100_f64, 200_f64), calculate_idle_values("100 0 100 100"), "Failed to properly calculate idle/non-idle for /proc/stat CPU with 4 values" ); assert_eq!( (120_f64, 200_f64), calculate_idle_values("100 0 100 100 20"), "Failed to properly calculate idle/non-idle for /proc/stat CPU with 5 values" ); assert_eq!( (120_f64, 230_f64), calculate_idle_values("100 0 100 100 20 30"), "Failed to properly calculate idle/non-idle for /proc/stat CPU with 6 values" ); assert_eq!( (120_f64, 270_f64), calculate_idle_values("100 0 100 100 20 30 40"), "Failed to properly calculate idle/non-idle for /proc/stat CPU with 7 values" ); assert_eq!( (120_f64, 320_f64), calculate_idle_values("100 0 100 100 20 30 40 50"), "Failed to properly calculate idle/non-idle for /proc/stat CPU with 8 values" ); assert_eq!( (120_f64, 320_f64), calculate_idle_values("100 0 100 100 20 30 40 50 100"), "Failed to properly calculate idle/non-idle for /proc/stat CPU with 9 values" ); assert_eq!( (120_f64, 320_f64), calculate_idle_values("100 0 100 100 20 30 40 50 100 200"), "Failed to properly calculate idle/non-idle for /proc/stat CPU with 10 values" ); } }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/processes/windows.rs
src-tauri/src/data_harvester/processes/windows.rs
//! Process data collection for Windows. Uses sysinfo. use sysinfo::{CpuExt, PidExt, ProcessExt, System, SystemExt}; use super::ProcessHarvest; pub fn get_process_data( sys: &System, use_current_cpu_total: bool, unnormalized_cpu: bool, mem_total_kb: u64, ) -> crate::utils::error::Result<Vec<ProcessHarvest>> { let mut process_vector: Vec<ProcessHarvest> = Vec::new(); let process_hashmap = sys.processes(); let cpu_usage = sys.global_cpu_info().cpu_usage() as f64 / 100.0; let num_processors = sys.cpus().len(); for process_val in process_hashmap.values() { let name = if process_val.name().is_empty() { let process_cmd = process_val.cmd(); if process_cmd.len() > 1 { process_cmd[0].clone() } else { let process_exe = process_val.exe().file_stem(); if let Some(exe) = process_exe { let process_exe_opt = exe.to_str(); if let Some(exe_name) = process_exe_opt { exe_name.to_string() } else { "".to_string() } } else { "".to_string() } } } else { process_val.name().to_string() }; let command = { let command = process_val.cmd().join(" "); if command.is_empty() { name.to_string() } else { command } }; let pcu = { let usage = process_val.cpu_usage() as f64; if unnormalized_cpu || num_processors == 0 { usage } else { usage / (num_processors as f64) } }; let process_cpu_usage = if use_current_cpu_total && cpu_usage > 0.0 { pcu / cpu_usage } else { pcu }; let disk_usage = process_val.disk_usage(); let process_state = (process_val.status().to_string(), 'R'); process_vector.push(ProcessHarvest { pid: process_val.pid().as_u32() as _, parent_pid: process_val.parent().map(|p| p.as_u32() as _), name, command, mem_usage_percent: if mem_total_kb > 0 { process_val.memory() as f64 * 100.0 / mem_total_kb as f64 } else { 0.0 }, mem_usage_bytes: process_val.memory(), cpu_usage_percent: process_cpu_usage, read_bytes_per_sec: disk_usage.read_bytes, write_bytes_per_sec: disk_usage.written_bytes, total_read_bytes: disk_usage.total_read_bytes, total_write_bytes: disk_usage.total_written_bytes, process_state, }); } Ok(process_vector) }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/processes/freebsd.rs
src-tauri/src/data_harvester/processes/freebsd.rs
//! Process data collection for FreeBSD. Uses sysinfo. use std::io; use serde::{Deserialize, Deserializer}; use sysinfo::System; use super::ProcessHarvest; use crate::data_harvester::deserialize_xo; use crate::data_harvester::processes::UserTable; #[derive(Deserialize, Debug, Default)] #[serde(rename_all = "kebab-case")] struct ProcessInformation { process: Vec<ProcessRow>, } #[derive(Deserialize, Debug)] #[serde(rename_all = "kebab-case")] struct ProcessRow { #[serde(deserialize_with = "pid")] pid: i32, #[serde(deserialize_with = "percent_cpu")] percent_cpu: f64, } pub fn get_process_data( sys: &System, use_current_cpu_total: bool, unnormalized_cpu: bool, mem_total_kb: u64, user_table: &mut UserTable, ) -> crate::utils::error::Result<Vec<ProcessHarvest>> { super::macos_freebsd::get_process_data( sys, use_current_cpu_total, unnormalized_cpu, mem_total_kb, user_table, get_freebsd_process_cpu_usage, ) } fn get_freebsd_process_cpu_usage(pids: &[i32]) -> io::Result<std::collections::HashMap<i32, f64>> { if pids.is_empty() { return Ok(std::collections::HashMap::new()); } let output = std::process::Command::new("ps") .args(["--libxo", "json", "-o", "pid,pcpu", "-p"]) .args(pids.iter().map(i32::to_string)) .output()?; deserialize_xo("process-information", &output.stdout).map(|process_info: ProcessInformation| { process_info .process .into_iter() .map(|row| (row.pid, row.percent_cpu)) .collect() }) } fn pid<'de, D>(deserializer: D) -> Result<i32, D::Error> where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?; s.parse().map_err(serde::de::Error::custom) } fn percent_cpu<'de, D>(deserializer: D) -> Result<f64, D::Error> where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?; s.parse().map_err(serde::de::Error::custom) }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
acarl005/toerings
https://github.com/acarl005/toerings/blob/24a55caf70cb19b0e7f5f88119012d8ae503b5d8/src-tauri/src/data_harvester/processes/macos/sysctl_bindings.rs
src-tauri/src/data_harvester/processes/macos/sysctl_bindings.rs
//! Partial bindings from Apple's open source code for getting process information. //! Some of this is based on [heim's binding implementation](https://github.com/heim-rs/heim/blob/master/heim-process/src/sys/macos/bindings/process.rs). use std::mem; use anyhow::{bail, Result}; use libc::{ boolean_t, c_char, c_long, c_short, c_uchar, c_ushort, c_void, dev_t, gid_t, itimerval, pid_t, rusage, sigset_t, timeval, uid_t, xucred, CTL_KERN, KERN_PROC, KERN_PROC_PID, MAXCOMLEN, }; use mach2::vm_types::user_addr_t; use crate::Pid; #[allow(non_camel_case_types)] #[repr(C)] pub(crate) struct kinfo_proc { pub kp_proc: extern_proc, pub kp_eproc: eproc, } #[allow(non_camel_case_types)] #[repr(C)] #[derive(Copy, Clone)] pub struct p_st1 { /// Doubly-linked run/sleep queue. p_forw: user_addr_t, p_back: user_addr_t, } #[allow(non_camel_case_types)] #[repr(C)] pub union p_un { pub p_st1: p_st1, /// process start time pub p_starttime: timeval, } /// Exported fields for kern sysctl. See /// [`proc.h`](https://opensource.apple.com/source/xnu/xnu-201/bsd/sys/proc.h) #[allow(non_camel_case_types)] #[repr(C)] pub(crate) struct extern_proc { pub p_un: p_un, /// Address space. pub p_vmspace: *mut vmspace, /// Signal actions, state (PROC ONLY). Should point to /// a `sigacts` but we don't really seem to need this. pub p_sigacts: user_addr_t, /// P_* flags. pub p_flag: i32, /// S* process status. pub p_stat: c_char, /// Process identifier. pub p_pid: pid_t, /// Save parent pid during ptrace. pub p_oppid: pid_t, /// Sideways return value from fdopen. pub p_dupfd: i32, /// where user stack was allocated pub user_stack: caddr_t, /// Which thread is exiting? pub exit_thread: *mut c_void, /// allow to debug pub p_debugger: i32, /// indication to suspend pub sigwait: boolean_t, /// Time averaged value of p_cpticks. pub p_estcpu: u32, /// Ticks of cpu time. pub p_cpticks: i32, /// %cpu for this process during p_swtime pub p_pctcpu: fixpt_t, /// Sleep address. pub p_wchan: *mut c_void, /// Reason for sleep. pub p_wmesg: *mut c_char, /// Time swapped in or out. pub p_swtime: u32, /// Time since last blocked. pub p_slptime: u32, /// Alarm timer. pub p_realtimer: itimerval, /// Real time. pub p_rtime: timeval, /// Statclock hit in user mode. pub p_uticks: u64, /// Statclock hits in system mode. pub p_sticks: u64, /// Statclock hits processing intr. pub p_iticks: u64, /// Kernel trace points. pub p_traceflag: i32, /// Trace to vnode. Originally a pointer to a struct of vnode. pub p_tracep: *mut c_void, /// DEPRECATED. pub p_siglist: i32, /// Vnode of executable. Originally a pointer to a struct of vnode. pub p_textvp: *mut c_void, /// If non-zero, don't swap. pub p_holdcnt: i32, /// DEPRECATED. pub p_sigmask: sigset_t, /// Signals being ignored. pub p_sigignore: sigset_t, /// Signals being caught by user. pub p_sigcatch: sigset_t, /// Process priority. pub p_priority: c_uchar, /// User-priority based on p_cpu and p_nice. pub p_usrpri: c_uchar, /// Process "nice" value. pub p_nice: c_char, pub p_comm: [c_char; MAXCOMLEN + 1], /// Pointer to process group. Originally a pointer to a `pgrp`. pub p_pgrp: *mut c_void, /// Kernel virtual addr of u-area (PROC ONLY). Originally a pointer to a `user`. pub p_addr: *mut c_void, /// Exit status for wait; also stop signal. pub p_xstat: c_ushort, /// Accounting flags. pub p_acflag: c_ushort, /// Exit information. XXX pub p_ru: *mut rusage, } const WMESGLEN: usize = 7; const COMAPT_MAXLOGNAME: usize = 12; /// See `_caddr_t.h`. #[allow(non_camel_case_types)] type caddr_t = *const libc::c_char; /// See `types.h`. #[allow(non_camel_case_types)] type segsz_t = i32; /// See `types.h`. #[allow(non_camel_case_types)] type fixpt_t = u32; /// See [`proc.h`](https://opensource.apple.com/source/xnu/xnu-201/bsd/sys/proc.h) #[allow(non_camel_case_types)] #[repr(C)] pub(crate) struct pcred { pub pc_lock: [c_char; 72], pub pc_ucred: *mut xucred, pub p_ruid: uid_t, pub p_svuid: uid_t, pub p_rgid: gid_t, pub p_svgid: gid_t, pub p_refcnt: i32, } /// See `vm.h`. #[allow(non_camel_case_types)] #[repr(C)] pub(crate) struct vmspace { pub dummy: i32, pub dummy2: caddr_t, pub dummy3: [i32; 5], pub dummy4: [caddr_t; 3], } /// See [`sysctl.h`](https://opensource.apple.com/source/xnu/xnu-344/bsd/sys/sysctl.h). #[allow(non_camel_case_types)] #[repr(C)] pub(crate) struct eproc { /// Address of proc. We just cheat and use a c_void pointer since we aren't using this. pub e_paddr: *mut c_void, /// Session pointer. We just cheat and use a c_void pointer since we aren't using this. pub e_sess: *mut c_void, /// Process credentials pub e_pcred: pcred, /// Current credentials pub e_ucred: xucred, /// Address space pub e_vm: vmspace, /// Parent process ID pub e_ppid: pid_t, /// Process group ID pub e_pgid: pid_t, /// Job control counter pub e_jobc: c_short, /// Controlling tty dev pub e_tdev: dev_t, /// tty process group id pub e_tpgid: pid_t, /// tty session pointer. We just cheat and use a c_void pointer since we aren't using this. pub e_tsess: *mut c_void, /// wchan message pub e_wmesg: [c_char; WMESGLEN + 1], /// text size pub e_xsize: segsz_t, /// text rss pub e_xrssize: c_short, /// text references pub e_xccount: c_short, pub e_xswrss: c_short, pub e_flag: c_long, /// short setlogin() name pub e_login: [c_char; COMAPT_MAXLOGNAME], pub e_spare: [c_long; 4], } /// Obtains the [`kinfo_proc`] given a process PID. /// /// From [heim](https://github.com/heim-rs/heim/blob/master/heim-process/src/sys/macos/bindings/process.rs#L235). pub(crate) fn kinfo_process(pid: Pid) -> Result<kinfo_proc> { let mut name: [i32; 4] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, pid]; let mut size = mem::size_of::<kinfo_proc>(); let mut info = mem::MaybeUninit::<kinfo_proc>::uninit(); let result = unsafe { libc::sysctl( name.as_mut_ptr(), 4, info.as_mut_ptr() as *mut libc::c_void, &mut size, std::ptr::null_mut(), 0, ) }; if result < 0 { bail!("failed to get process for pid {pid}"); } // sysctl succeeds but size is zero, happens when process has gone away if size == 0 { bail!("failed to get process for pid {pid}"); } unsafe { Ok(info.assume_init()) } } #[cfg(test)] mod test { use std::mem; use super::*; /// A quick test to ensure that things are sized correctly. #[test] fn test_struct_sizes() { assert_eq!(mem::size_of::<p_st1>(), 16); assert_eq!(mem::align_of::<p_st1>(), 8); assert_eq!(mem::size_of::<pcred>(), 104); assert_eq!(mem::align_of::<pcred>(), 8); assert_eq!(mem::size_of::<vmspace>(), 64); assert_eq!(mem::align_of::<vmspace>(), 8); assert_eq!(mem::size_of::<extern_proc>(), 296); assert_eq!(mem::align_of::<extern_proc>(), 8); assert_eq!(mem::size_of::<eproc>(), 376); assert_eq!(mem::align_of::<eproc>(), 8); assert_eq!(mem::size_of::<kinfo_proc>(), 672); assert_eq!(mem::align_of::<kinfo_proc>(), 8); } }
rust
MIT
24a55caf70cb19b0e7f5f88119012d8ae503b5d8
2026-01-04T20:17:23.288089Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/lib.rs
crates/axl-runtime/src/lib.rs
#![allow(clippy::new_without_default)] mod builtins; pub mod engine; pub mod eval; pub mod module;
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/builtins/mod.rs
crates/axl-runtime/src/builtins/mod.rs
use std::path::PathBuf; #[cfg(debug_assertions)] pub fn expand_builtins( _root_dir: PathBuf, _broot: PathBuf, ) -> std::io::Result<Vec<(String, PathBuf)>> { // Use CARGO_MANIFEST_DIR to locate builtins relative to this crate's source, // not the user's project root (which could be /tmp or anywhere) let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); Ok(vec![( "aspect".to_string(), manifest_dir.join("src/builtins/aspect"), )]) } #[cfg(not(debug_assertions))] pub fn expand_builtins( _root_dir: PathBuf, broot: PathBuf, ) -> std::io::Result<Vec<(String, PathBuf)>> { use aspect_telemetry::cargo_pkg_version; use std::fs; let builtins_root = broot.join(sha256::digest(cargo_pkg_version())); fs::create_dir_all(&builtins_root)?; let builtins = vec![ ("aspect/build.axl", include_str!("./aspect/build.axl")), ("aspect/test.axl", include_str!("./aspect/test.axl")), ("aspect/axl_add.axl", include_str!("./aspect/axl_add.axl")), ( "aspect/MODULE.aspect", include_str!("./aspect/MODULE.aspect"), ), ]; for (path, content) in builtins { let out_path = &builtins_root.join(path); fs::create_dir_all(&out_path.parent().unwrap())?; fs::write(out_path, content)?; } Ok(vec![("aspect".to_string(), builtins_root.join("aspect"))]) }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/eval/config.rs
crates/axl-runtime/src/eval/config.rs
use anyhow::anyhow; use starlark::environment::Module; use starlark::eval::Evaluator; use starlark::values::{Heap, Value, ValueLike}; use std::path::Path; use crate::engine::config::{ConfigContext, TaskMut}; use crate::eval::load::{AxlLoader, ModuleScope}; use crate::eval::load_path::join_confined; use super::error::EvalError; /// Evaluator for running config.axl files.a #[derive(Debug)] pub struct ConfigEvaluator<'l, 'p> { loader: &'l AxlLoader<'p>, } impl<'l, 'p> ConfigEvaluator<'l, 'p> { /// Creates a new AxlScriptEvaluator with the given module root. pub fn new(loader: &'l AxlLoader<'p>) -> Self { Self { loader } } /// Evaluates the given .axl script path relative to the module root, returning /// the evaluated script or an error. Performs security checks to ensure the script /// file is within the module root. pub fn eval(&self, scope: ModuleScope, path: &Path) -> Result<Module, EvalError> { assert!(path.is_relative()); let abs_path = join_confined(&scope.path, path)?; // push the current scope to stack self.loader.module_stack.borrow_mut().push(scope); let module = self.loader.eval_module(&abs_path)?; // pop the current let _scope = self .loader .module_stack .borrow_mut() .pop() .expect("just pushed a scope"); // Return the evaluated script Ok(module) } /// Evaluates the given .axl script path relative to the module root, returning /// the evaluated script or an error. Performs security checks to ensure the script /// file is within the module root. pub fn run_all<'v>( &'v self, scope: ModuleScope, paths: Vec<&Path>, tasks: Vec<TaskMut<'v>>, ) -> Result<&'v ConfigContext<'v>, EvalError> { self.loader.module_stack.borrow_mut().push(scope.clone()); let eval_module = Box::leak(Box::new(Module::new())); let context_module = Box::leak(Box::new(Module::new())); let heap: &'v Heap = unsafe { std::mem::transmute::<&Heap, &'v Heap>(context_module.heap()) }; let context = heap.alloc(ConfigContext::new(tasks, heap)); let ctx = context.downcast_ref::<ConfigContext<'v>>().unwrap(); for path in paths { assert!(path.is_absolute()); let rel_path = path .strip_prefix(&scope.path) .map_err(|e| EvalError::UnknownError(anyhow!("Failed to strip prefix: {e}")))? .to_path_buf(); let config_module = self.eval(scope.clone(), &rel_path)?; let frozen = config_module .freeze() .map_err(|e| EvalError::UnknownError(anyhow!(e)))?; let def = frozen .get("config") .map_err(|_| EvalError::MissingSymbol("config".into()))?; let func = def.value(); // Adjust the lifetime of func to 'v so it can be used within eval.eval_function below. // This is necessary because the type system prevents mixing Values from different heaps // without it, but in this case for the lifetime of frozen function called for side effects // on a shared context, it is safe in practice. let func = unsafe { std::mem::transmute::<Value, Value<'v>>(func) }; let store = self.loader.new_store(path.to_path_buf()); let mut eval = Evaluator::new(eval_module); eval.set_loader(self.loader); eval.extra = Some(&store); eval.eval_function(func, &[context], &[])?; drop(eval); drop(store); ctx.add_config_module(frozen); } // Set and freeze initial configs if not set let mut to_set: Vec<(&'v TaskMut<'v>, Value<'v>)> = Vec::new(); for task in ctx.tasks() { let config = *task.config.borrow(); if config.is_none() { let initial = task.initial_config(); to_set.push((task, initial)); } } for (task, initial) in to_set { let temp_module = Module::new(); let short_initial: Value = unsafe { std::mem::transmute(initial) }; temp_module.set("temp", short_initial); let frozen = temp_module.freeze().expect("freeze failed"); let frozen_val: Value<'v> = unsafe { std::mem::transmute(frozen.get("temp").expect("get").value()) }; task.config.replace(frozen_val); *task.frozen_config_module.borrow_mut() = Some(frozen); } self.loader.module_stack.borrow_mut().pop(); Ok(ctx) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/eval/error.rs
crates/axl-runtime/src/eval/error.rs
use thiserror::Error; /// Enum representing possible errors during evaluation, including Starlark-specific errors, /// missing symbols, and wrapped anyhow or IO errors. #[derive(Error, Debug)] #[non_exhaustive] pub enum EvalError { #[error("{0}")] StarlarkError(starlark::Error), #[error("{0:?}")] FreezeError(starlark::values::FreezeError), #[error("script does not export {0:?} symbol")] MissingSymbol(String), #[error(transparent)] UnknownError(#[from] anyhow::Error), #[error(transparent)] IOError(#[from] std::io::Error), } // Custom From implementation since starlark::Error doesn't implement std::error::Error. impl From<starlark::Error> for EvalError { fn from(value: starlark::Error) -> Self { Self::StarlarkError(value) } } impl Into<starlark::Error> for EvalError { fn into(self) -> starlark::Error { match self { EvalError::StarlarkError(error) => error, EvalError::MissingSymbol(_) => starlark::Error::new_other(self), EvalError::UnknownError(error) => starlark::Error::new_other(error), EvalError::IOError(error) => starlark::Error::new_other(error), EvalError::FreezeError(error) => starlark::Error::new_other(error), } } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/eval/api.rs
crates/axl-runtime/src/eval/api.rs
use crate::engine; use starlark::environment::{GlobalsBuilder, LibraryExtension}; use starlark::syntax::{Dialect, DialectTypes}; /// Returns a GlobalsBuilder for AXL globals, extending various Starlark library extensions /// with custom top-level functions registered from the engine module. pub fn get_globals() -> GlobalsBuilder { let mut globals = GlobalsBuilder::extended_by(&[ LibraryExtension::Breakpoint, LibraryExtension::CallStack, LibraryExtension::Debug, LibraryExtension::EnumType, LibraryExtension::Filter, LibraryExtension::Json, LibraryExtension::Map, LibraryExtension::NamespaceType, LibraryExtension::Partial, LibraryExtension::Pprint, LibraryExtension::Prepr, LibraryExtension::Print, LibraryExtension::Pstr, LibraryExtension::RecordType, LibraryExtension::SetType, LibraryExtension::StructType, LibraryExtension::Typing, ]); engine::register_globals(&mut globals); globals } pub fn dialect() -> Dialect { Dialect { enable_def: true, enable_lambda: true, enable_load: true, enable_load_reexport: true, enable_keyword_only_arguments: true, enable_positional_only_arguments: true, enable_types: DialectTypes::Enable, enable_f_strings: true, enable_top_level_stmt: true, ..Default::default() } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/eval/mod.rs
crates/axl-runtime/src/eval/mod.rs
mod api; pub mod config; mod error; mod load; mod load_path; pub mod task; pub use api::get_globals; pub use error::EvalError; pub use load::AxlLoader as Loader; pub use load::ModuleScope; pub(crate) use load_path::validate_module_name;
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/eval/task.rs
crates/axl-runtime/src/eval/task.rs
use anyhow::anyhow; use starlark::environment::Module; use starlark::eval::Evaluator; use starlark::values::Heap; use starlark::values::ValueLike; use std::path::Path; use crate::engine::config::TaskMut; use crate::engine::store::AxlStore; use crate::engine::task::Task; use crate::engine::task::{AsTaskLike, FrozenTask, TaskLike}; use crate::engine::task_args::TaskArgs; use crate::engine::task_context::TaskContext; use super::error::EvalError; use super::load::{AxlLoader, ModuleScope}; use super::load_path::join_confined; pub trait TaskModuleLike { fn tasks(&self) -> Vec<&str>; fn has_task(&self, symbol: &str) -> bool; fn has_name(&self, symbol: &str) -> bool; /// Retrieves a task definition from the evaluated module by symbol name. fn get_task(&self, symbol: &str) -> Result<&dyn TaskLike, EvalError>; fn execute_task<'v>( &'v self, store: AxlStore, task: &TaskMut<'v>, args: impl FnOnce(&Heap) -> TaskArgs, ) -> Result<Option<u8>, EvalError>; } impl TaskModuleLike for Module { fn get_task(&self, symbol: &str) -> Result<&dyn TaskLike, EvalError> { let def = self .get(symbol) .ok_or(EvalError::MissingSymbol(symbol.to_string()))?; if let Some(task) = def.downcast_ref::<Task>() { return Ok(task.as_task()); } else if let Some(task) = def.downcast_ref::<FrozenTask>() { return Ok(task.as_task()); } else { return Err(EvalError::UnknownError(anyhow!("expected type of Task"))); } } fn tasks(&self) -> Vec<&str> { self.names() .filter(|symbol| self.has_task(symbol)) .map(|sym| sym.as_str()) .collect() } fn has_task(&self, symbol: &str) -> bool { let val = self.get(symbol); if let Some(val) = val { if val.downcast_ref::<Task>().is_none() && val.downcast_ref::<FrozenTask>().is_none() { return false; } return true; } false } fn has_name(&self, symbol: &str) -> bool { self.get(symbol).is_some() } /// Executes a task from the module by symbol, providing arguments and returning the exit code. fn execute_task<'v>( &'v self, store: AxlStore, task: &TaskMut<'v>, args: impl FnOnce(&Heap) -> TaskArgs, ) -> Result<Option<u8>, EvalError> { let heap = self.heap(); let args = args(heap); let config = *task.config.borrow(); let context = heap.alloc(TaskContext::new(args, config)); let mut eval = Evaluator::new(self); eval.extra = Some(&store); let original = self .get(&task.symbol) .expect("symbol should have been defined."); let ret = if let Some(val) = original.downcast_ref::<Task>() { eval.eval_function(val.implementation(), &[context], &[])? } else if let Some(val) = original.downcast_ref::<FrozenTask>() { eval.eval_function(val.implementation().to_value(), &[context], &[])? } else { return Err(EvalError::UnknownError(anyhow::anyhow!( "expected value of type Task" ))); }; drop(eval); Ok(ret.unpack_i32().map(|ex| ex as u8)) } } /// The core evaluator for .axl files, holding configuration like module root, /// Starlark dialect, globals, and store. Used to evaluate .axl files securely. #[derive(Debug)] pub struct TaskEvaluator<'l, 'p> { loader: &'l AxlLoader<'p>, } impl<'l, 'p> TaskEvaluator<'l, 'p> { /// Creates a new AxlScriptEvaluator with the given module root. pub fn new(loader: &'l AxlLoader<'p>) -> Self { Self { loader } } /// Evaluates the given .axl script path relative to the module root, returning /// the evaluated script or an error. Performs security checks to ensure the script /// file is within the module root. pub fn eval(&self, scope: ModuleScope, path: &Path) -> Result<Module, EvalError> { assert!(path.is_relative()); let abs_path = join_confined(&scope.path, path)?; // push the current scope to stack self.loader.module_stack.borrow_mut().push(scope); let module = self.loader.eval_module(&abs_path)?; // pop the current scope off the stack let _scope = self .loader .module_stack .borrow_mut() .pop() .expect("just pushed a scope"); // Return the evaluated script Ok(module) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/eval/load.rs
crates/axl-runtime/src/eval/load.rs
use anyhow::anyhow; use starlark::environment::{FrozenModule, Globals, Module}; use starlark::eval::{Evaluator, FileLoader}; use starlark::syntax::{AstModule, Dialect}; use std::cell::RefCell; use std::collections::HashMap; use std::fs; use std::path::{Path, PathBuf}; use super::api; use super::error::EvalError; use super::load_path::{join_confined, LoadPath}; use crate::engine::store::AxlStore; #[derive(Debug, Clone)] pub struct ModuleScope { // The current module name that the load statement is in pub name: String, // The module root directory that relative loads cannot escape pub path: PathBuf, } /// Internal loader for .axl files, handling path resolution, security checks, and recursive loading. #[derive(Debug)] pub struct AxlLoader<'p> { pub(super) cli_version: &'p String, pub(super) repo_root: &'p PathBuf, // The deps root directory where module expander expanded all the modules. pub(super) deps_root: &'p PathBuf, pub(crate) dialect: Dialect, pub(crate) globals: Globals, // stack variables pub(crate) load_stack: RefCell<Vec<PathBuf>>, pub(crate) module_stack: RefCell<Vec<ModuleScope>>, loaded_modules: RefCell<HashMap<PathBuf, FrozenModule>>, } impl<'p> AxlLoader<'p> { pub fn new(cli_version: &'p String, repo_root: &'p PathBuf, deps_root: &'p PathBuf) -> Self { Self { cli_version, repo_root, deps_root, dialect: api::dialect(), globals: api::get_globals().build(), load_stack: RefCell::new(vec![]), module_stack: RefCell::new(vec![]), loaded_modules: RefCell::new(HashMap::new()), } } pub fn new_store(&self, path: PathBuf) -> AxlStore { AxlStore::new(self.cli_version.clone(), self.repo_root.clone(), path) } pub(super) fn eval_module(&self, path: &Path) -> Result<Module, EvalError> { assert!(path.is_absolute()); // Push the script path onto the LOAD_STACK (used to detect circular loads) self.load_stack.borrow_mut().push(path.to_path_buf()); // Load and evaluate the script let raw = fs::read_to_string(&path)?; let ast = AstModule::parse(&path.to_string_lossy(), raw, &self.dialect)?; let module = Module::new(); let store = self.new_store(path.to_path_buf()); let mut eval = Evaluator::new(&module); eval.set_loader(self); eval.extra = Some(&store); eval.eval_module(ast, &self.globals)?; drop(eval); drop(store); // Pop the script path off of the LOAD_STACK self.load_stack.borrow_mut().pop(); // Return the evaluated script Ok(module) } fn resolve_in_deps_root( &self, module_name: &str, module_subpath: &Path, ) -> anyhow::Result<PathBuf> { let module_root = self.deps_root.join(module_name); if !module_root.exists() { return Err(anyhow!("module '{}' is not declared.", module_name,)); } let resolved_path = join_confined(&module_root, module_subpath)?; if !resolved_path.is_file() { return Err(anyhow!( "path '{:?}' does not exist in module `{}`.", module_subpath, module_name, )); } Ok(resolved_path) } fn resolve(&self, module_root: &Path, subpath: &Path) -> anyhow::Result<PathBuf> { join_confined(&module_root, subpath) } } impl<'p> FileLoader for AxlLoader<'p> { fn load(&self, raw: &str) -> starlark::Result<FrozenModule> { let load_path: LoadPath = raw.try_into()?; let load_stack = self.load_stack.borrow(); let module_stack = self.module_stack.borrow(); let parent_script_path = load_stack.last().expect("stack should not be empty"); let module_info = module_stack .last() .expect("module name stack should not be empty"); let resolved_script_path = match &load_path { LoadPath::ModuleSpecifier { module, subpath } => { self.resolve_in_deps_root(&module, &subpath)? } LoadPath::ModuleSubpath(subpath) => self.resolve(&module_info.path, subpath)?, LoadPath::RelativePath(relpath) => { let parent = parent_script_path .strip_prefix(&module_info.path) .expect("parent script path should have same prefix as current module"); if let Some(parent) = parent.parent() { self.resolve(&module_info.path, &parent.join(relpath))? } else { self.resolve(&module_info.path, relpath)? } } }; // If the module is already loaded, then just return it. if let Some(cached_module) = self .loaded_modules .borrow() .get(&resolved_script_path) .cloned() { return Ok(cached_module); } // Detect cycles and prevent loading the same file recursively. if load_stack.contains(&resolved_script_path) { let stack_str = load_stack .iter() .map(|p| format!("- {}", p.display())) .collect::<Vec<_>>() .join("\n"); return Err(starlark::Error::new_other(anyhow!( "cycle detected in load path:\n{}\n(cycles back to {:?})", stack_str, resolved_script_path ))); } drop(load_stack); // Push the resolved path to the stack so that relative imports from the file still works. // load_stack.push(resolved_script_path.clone()); // Read and parse the file content into an AST. let frozen_module = self .eval_module(&resolved_script_path) .map_err(|e| Into::<starlark::Error>::into(e))? .freeze()?; // Pop the load stack after successful load // self.load_stack.borrow_mut().pop(); // Cache the load @module//path/to/file.axl so it can be re-used on subsequent loads self.loaded_modules .borrow_mut() .insert(resolved_script_path, frozen_module.clone()); Ok(frozen_module) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/eval/load_path.rs
crates/axl-runtime/src/eval/load_path.rs
use std::path::{Component, Path, PathBuf}; use anyhow::anyhow; /// Joins two paths ensuring that the subpath does not lead to oustide of base. pub(super) fn join_confined(base: &Path, subpath: &Path) -> anyhow::Result<PathBuf> { let mut dest = base.to_path_buf(); for component in subpath.components() { match component { Component::CurDir => {} Component::ParentDir => { if dest == base { return Err(anyhow!("subpath {:?} is outside of {:?}", subpath, base)); } dest.pop(); } Component::Normal(s) => { dest.push(s); } comp => { return Err(anyhow!( "invalid component `{:?}` in path: {:?}", comp, subpath )); } } } Ok(dest) } /// Validates a module name according to the following rules: /// - Must not be empty. /// - Must begin with a lowercase letter (a-z). /// - Must end with a lowercase letter (a-z) or digit (0-9). /// - Can only contain lowercase letters (a-z), digits (0-9), dots (.), hyphens (-), and underscores (_). /// /// # Arguments /// * `module_name` - The module name string to validate. /// /// # Returns /// * `Ok(())` if the module name is valid. /// * `Err(starlark::Error)` with a descriptive error if invalid. pub fn validate_module_name(module_name: &str) -> anyhow::Result<()> { if module_name.is_empty() { return Err(anyhow!("module name cannot be empty")); } // Begins with lowercase letter let first_char = module_name.chars().next().unwrap(); if !first_char.is_ascii_lowercase() { return Err(anyhow!("module name must begin with a lowercase letter")); } // Ends with lowercase letter or digit let last_char = module_name.chars().last().unwrap(); if !last_char.is_ascii_lowercase() && !last_char.is_ascii_digit() { return Err(anyhow!( "module name must end with a lowercase letter or digit" )); } // Only allowed characters let allowed = "abcdefghijklmnopqrstuvwxyz0123456789.-_"; for c in module_name.chars() { if !allowed.contains(c) { return Err(anyhow!("module name contains invalid character: '{}'", c)); } } Ok(()) } /// Normalizes an absolute path by removing redundant '.' components and resolving '..' components against preceding normal components where possible. /// Ensures the path is absolute and that the first segment after the root is not '.' or '..'. /// Ignores extra '..' components that would go beyond the root without preserving them. /// This normalization is purely syntactic and does not interact with the filesystem. /// TODO: switch to Path.normalize_lexically in the future once it is in a stable Rust release: https://github.com/rust-lang/rust/issues/134694. /// /// # Arguments /// * `path` - The absolute path to normalize. /// /// # Returns /// * `Ok(PathBuf)` containing the normalized path if valid. /// * `Err(starlark::Error)` if the path is not absolute or starts with an invalid segment after the root. // pub fn normalize_abs_path_lexically(path: &Path) -> anyhow::Result<PathBuf> { // if !path.is_absolute() { // return Err(anyhow!("path is not absolute: {}", path.display())); // } // let mut iter = path.components(); // if iter.next() != Some(Component::RootDir) { // return Err(anyhow!("path does not start with root directory")); // } // let next = iter.next(); // if matches!(next, Some(Component::CurDir) | Some(Component::ParentDir)) { // return Err(anyhow!( // "absolute path starts with invalid segment '.' or '..'" // )); // } // let mut components = vec![Component::RootDir]; // if let Some(c) = next { // components.push(c); // } // for component in iter { // match component { // Component::ParentDir => { // if !components.is_empty() && matches!(components.last(), Some(Component::Normal(_))) // { // components.pop(); // } // // Ignore if at root; do not push // } // Component::CurDir => {} // _ => components.push(component), // } // } // let mut result = PathBuf::new(); // for c in components { // result.push(c.as_os_str()); // } // Ok(result) // } /// Normalizes a relative path by removing redundant '.' components and resolving '..' components against preceding normal components where possible. /// Unresolvable '..' components (e.g., at the beginning or following other '..') are preserved to maintain the relative nature of the path. /// If the original path starts with './' and the normalized path does not begin with '.' or '..', the leading './' is preserved for explicit current directory reference. /// This normalization is purely syntactic and does not interact with the filesystem. fn normalize_rel_path_lexically(path: &Path) -> PathBuf { let starts_with_cur = path.components().next() == Some(Component::CurDir); let mut components = Vec::new(); for component in path.components() { match component { Component::ParentDir => { if !components.is_empty() && matches!(components.last(), Some(Component::Normal(_))) { components.pop(); } else { components.push(component); } } Component::CurDir => {} _ => components.push(component), } } let mut result = PathBuf::new(); for c in components { result.push(c.as_os_str()); } let first_comp = result.components().next(); if starts_with_cur && first_comp != Some(Component::ParentDir) && first_comp != Some(Component::CurDir) { PathBuf::from(".").join(&result) } else { result } } /// Validates a path segment to ensure it is a valid filename compatible with Linux, macOS, and Windows. /// Checks include: /// - Not empty. /// - Length <= 255 bytes. /// - Does not end with space or dot. /// - Not a reserved Windows device name (e.g., CON, PRN, etc., case-insensitive, including extensions like CON.txt). /// - No control characters or invalid characters: \, /, :, *, ?, ", <, >, |. /// - No leading or trailing whitespace for cross-platform safety. /// /// # Arguments /// * `segment` - The path segment string to validate. /// /// # Returns /// * `Ok(())` if the segment is valid. /// * `Err(starlark::Error)` with a descriptive error if invalid. fn validate_path_segment(segment: &str) -> anyhow::Result<()> { if segment.is_empty() { return Err(anyhow!("empty path segment disallowed")); } if segment.trim() != segment { return Err(anyhow!( "path segment '{}' contains leading or trailing whitespace, which is disallowed for cross-platform safety", segment )); } if segment.as_bytes().len() > 255 { return Err(anyhow!("path segment '{}' exceeds 255 bytes", segment)); } if segment.ends_with(' ') || segment.ends_with('.') { return Err(anyhow!( "path segment '{}' ends with disallowed character (space or dot)", segment )); } let upper = segment.to_uppercase(); let base = upper.splitn(2, '.').next().unwrap(); // These are reserved device names in Windows (case-insensitive) that cannot be used as filenames. // They refer to system devices: CON (console), PRN (printer), AUX (auxiliary), NUL (null), // COM0-COM9 (serial ports), LPT0-LPT9 (parallel ports). // We check the base name (before the first dot) to catch names like "CON.txt". let reserved = [ "CON", "PRN", "AUX", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", ]; if reserved.contains(&base) { return Err(anyhow!( "reserved name '{}' disallowed in path segment", segment )); } for c in segment.chars() { if c.is_control() || matches!(c, '\\' | '/' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { return Err(anyhow!( "invalid character '{}' in path segment '{}'", c, segment )); } } Ok(()) } /// Enum representing a sanitized load path, which can be: /// - A full module specifier like "@module_name//path/to/file.axl". /// - A module subpath like "path/to/file.axl". /// - A relative path like "./path/to/file.axl" or "../path/to/file.axl". #[derive(Debug, Clone, PartialEq, Eq)] pub enum LoadPath { ModuleSpecifier { module: String, subpath: PathBuf }, ModuleSubpath(PathBuf), RelativePath(PathBuf), } impl TryFrom<&str> for LoadPath { type Error = anyhow::Error; /// Sanitizes a load path string according to various rules and extracts components. /// Rules include: /// - No leading or trailing whitespace. /// - Does not start with '/'. /// - No '\' separators. /// - No double '//' separators except as the module separator in full module specifiers. /// - Does not start with '@@'. /// - Must end with a filename ending in '.axl'. /// - If a full module specifier (starts with '@module_name//'), validates the module name after '@' and before '//'. /// - Validates each path segment in the subpath as a valid filename. /// - Allows starting with a single './' and zero or more '../' in the initial relative prefix, but no multiple '.' segments and no '.' or '..' after normal segments. /// /// # Arguments /// * `load_path` - The load path string to validate. /// /// # Returns /// * `Ok(LoadPath)` containing the parsed and normalized load path. /// * `Err(starlark::Error)` with a descriptive error if any validation fails. fn try_from(load_path: &str) -> Result<Self, Self::Error> { if load_path.trim() != load_path { return Err(anyhow!( "paths starting or ending with whitespace are disallowed" )); } if load_path.starts_with('/') { return Err(anyhow!("paths starting with '/' are disallowed")); } if load_path.contains('\\') { return Err(anyhow!("paths containing '\\' separators are disallowed")); } if load_path.starts_with("@@") { return Err(anyhow!("paths starting with '@@' are disallowed")); } // Extract the filename as the part after the last '/', or the whole path if no '/' let filename = match load_path.rfind('/') { Some(pos) => &load_path[(pos + 1)..], None => &load_path, }; if filename.is_empty() || !filename.ends_with(".axl") { return Err(anyhow!( "load path must end with a filename ending in '.axl'" )); } let (module_name_option, path_to_validate): (Option<String>, &str) = if load_path.starts_with('@') { if let Some(double_pos) = load_path.find("//") { let candidate_module = &load_path[1..double_pos]; if candidate_module.find('/').is_none() { validate_module_name(candidate_module)?; ( Some(candidate_module.to_string()), &load_path[(double_pos + 2)..], ) } else { (None, load_path) } } else { (None, load_path) } } else { (None, load_path) }; // Check for disallowed double slashes if module_name_option.is_some() { if path_to_validate.contains("//") { return Err(anyhow!( "load paths with double slashes '//' are disallowed except for the module separator" )); } } else { if load_path.contains("//") { return Err(anyhow!( "load paths with double slashes '//' are disallowed" )); } } // Validate path segments after module (if present) let mut allowing_relative = true; let mut seen_dot = false; for segment in path_to_validate.split('/') { if allowing_relative { if segment == "." { if seen_dot { return Err(anyhow!("multiple '.' relative segments are disallowed")); } seen_dot = true; continue; } else if segment == ".." { continue; } else { allowing_relative = false; // fall through to validate } } validate_path_segment(segment)?; } let normalized_path = normalize_rel_path_lexically(Path::new(path_to_validate)); if let Some(module) = module_name_option { Ok(LoadPath::ModuleSpecifier { module, subpath: normalized_path, }) } else { let first_comp = normalized_path.components().next(); if matches!(first_comp, Some(Component::CurDir | Component::ParentDir)) { Ok(LoadPath::RelativePath(normalized_path)) } else { Ok(LoadPath::ModuleSubpath(normalized_path)) } } } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/module/disk_store.rs
crates/axl-runtime/src/module/disk_store.rs
use std::collections::HashMap; use std::{io, os::unix::ffi::OsStrExt, path::PathBuf, str::FromStr}; use anyhow::anyhow; use dirs::cache_dir; use flate2::read::GzDecoder; use futures_util::TryStreamExt; use rand::prelude::*; use reqwest::{self, Client, Method, Request, Url}; use ssri::{Algorithm, Integrity, IntegrityChecker, IntegrityOpts}; use thiserror::Error; use tokio::fs::{self, File}; use tokio::io::AsyncWriteExt; use crate::builtins; use super::store::ModuleStore; use super::{AxlArchiveDep, AxlLocalDep, Dep}; pub struct DiskStore { #[allow(unused)] root: PathBuf, root_sha: String, } #[derive(Error, Debug)] pub enum StoreError { #[error(transparent)] IoError(#[from] std::io::Error), #[error(transparent)] FetchError(#[from] reqwest::Error), #[error(transparent)] ChecksumError(#[from] ssri::Error), #[error("failed to unpack: {0}")] UnpackError(std::io::Error), #[error("failed to link: {0}")] LinkError(std::io::Error), #[error("missing integrity for module @{0}, set integrity = \"{1}\"")] MissingIntegrity(String, Integrity), } enum Processor { Check(IntegrityChecker), Hash(IntegrityOpts), } impl Processor { fn new_check(integrity: Integrity) -> Self { Processor::Check(IntegrityChecker::new(integrity)) } fn new_hash() -> Self { Processor::Hash(IntegrityOpts::new().algorithm(Algorithm::Sha512)) } fn update<B: AsRef<[u8]>>(&mut self, data: B) { match self { Processor::Check(checker) => checker.input(data), Processor::Hash(opts) => opts.input(data), } } fn finalize(self) -> Result<Option<Integrity>, ssri::Error> { match self { Processor::Check(checker) => checker.result().map(|_| None), Processor::Hash(opts) => Ok(Some(opts.result())), } } } impl DiskStore { pub fn new(root: PathBuf) -> Self { Self { root_sha: sha256::digest(root.as_os_str().as_bytes()), root, } } fn root(&self) -> PathBuf { cache_dir() .unwrap_or_else(|| PathBuf::from("/tmp")) .join("aspect") .join("axl") } pub fn deps_path(&self) -> PathBuf { self.root().join("deps").join(&self.root_sha) } fn dep_path(&self, dep: &str) -> PathBuf { self.deps_path().join(dep) } fn dep_marker_path(&self, dep: &Dep) -> PathBuf { self.deps_path().join(format!("{}@marker", dep.name())) } fn cas_path_for_integrity(&self, integrity: &Integrity) -> PathBuf { let hex = integrity.to_hex(); self.root().join("cas").join(hex.0.to_string()).join(hex.1) } fn download_tmp_file(&self) -> PathBuf { let mut rng = rand::thread_rng(); let mut bytes = [0u8; 32]; rng.fill_bytes(&mut bytes); let hex_string: String = bytes.iter().map(|b| format!("{:02x}", b)).collect(); self.root() .join("dl") .join(hex_string) .with_extension("tmp") } async fn fetch_dep( &self, client: &Client, dep: &AxlArchiveDep, url: &String, ) -> Result<Option<Integrity>, StoreError> { let compute_integrity = dep.integrity.is_none(); let tmp_file = self.download_tmp_file(); let mut tmp = File::create(&tmp_file).await?; let req = Request::new( Method::GET, Url::from_str(url.as_str()).expect("url should have been validated in axl_archive_dep"), ); let mut byte_stream = client .execute(req) .await? .error_for_status()? .bytes_stream(); let mut processor = if compute_integrity { Processor::new_hash() } else { Processor::new_check(dep.integrity.clone().unwrap()) }; while let Some(item) = byte_stream.try_next().await? { processor.update(&item); tmp.write_all(&item).await?; } let result = match processor.finalize() { Ok(res) => res, Err(err) => { let _ = fs::remove_file(&tmp_file).await; return Err(StoreError::ChecksumError(err)); } }; if compute_integrity { let _ = fs::remove_file(&tmp_file).await; Ok(result) } else { let integrity = dep.integrity.as_ref().unwrap(); let cas_path = self.cas_path_for_integrity(integrity); tokio::fs::rename(&tmp_file, &cas_path).await?; Ok(None) } } async fn expand_dep(&self, dep: &AxlArchiveDep) -> Result<(), io::Error> { let dep_path = self.dep_path(&dep.name); let integrity = dep.integrity.as_ref().expect("integrity must be set"); let cas_path = self.cas_path_for_integrity(integrity); let raw = File::open(&cas_path).await?; let raw = raw.into_std().await; let decoder = GzDecoder::new(raw); let mut archive = tar::Archive::new(decoder); let entries = archive.entries()?; let mut found_matching_entries = false; for entry in entries { let mut entry = entry?; let path = entry.path()?; if entry.link_name().is_ok_and(|f| f.is_some()) { // We don't know how to safely handle symlinks yet so forbid it // for now. // TODO: implement this with a chroot style symlink normalization. continue; } // If the strip_prefix is specified and entry does not start with it // skip the entry as we won't need it. if !dep.strip_prefix.is_empty() && !path.starts_with(&dep.strip_prefix) { continue; } // Set it to true since, there was at least one matching entry. found_matching_entries = true; let new_dst = path .strip_prefix(&dep.strip_prefix) .expect("entry must have had strip_prefix. please file a bug"); if new_dst.as_os_str().eq("/") || new_dst.as_os_str().eq("") { continue; } let new_dst_abs = dep_path.join(new_dst); entry.unpack(new_dst_abs)?; } if !dep.strip_prefix.is_empty() && !found_matching_entries { return Err(io::Error::new( io::ErrorKind::InvalidInput, anyhow!( "strip_prefix {} was provided but it does not match any entries.", dep.strip_prefix ), )); } Ok(()) } async fn link_dep(&self, dep: &AxlLocalDep) -> Result<(), io::Error> { let dep_path = self.dep_path(&dep.name); // Remove any existing symlink before creating a new one let _ = fs::remove_file(&dep_path).await; fs::symlink(&dep.path, dep_path).await } pub async fn expand_store( &self, store: &ModuleStore, ) -> Result<Vec<(String, PathBuf)>, StoreError> { let root = self.root(); fs::create_dir_all(&root).await?; fs::create_dir_all(self.deps_path()).await?; fs::create_dir_all(&root.join("cas")).await?; fs::create_dir_all(&root.join("dl")).await?; fs::create_dir_all(&root.join("builtins")).await?; let client = reqwest::Client::new(); let mut all: HashMap<String, Dep> = builtins::expand_builtins(self.root.clone(), root.join("builtins"))? .into_iter() .map(|(name, path)| { ( name.clone(), Dep::Local(AxlLocalDep { name: name, path: path, // Builtins tasks are always auto used auto_use_tasks: true, }), ) }) .collect(); all.extend(store.deps.take()); let mut module_roots = vec![]; for dep in all.values() { let dep_marker_path = self.dep_marker_path(&dep); let dep_path = self.dep_path(dep.name()); match dep { Dep::Local(local) if local.auto_use_tasks => { module_roots.push((local.name.clone(), dep_path.clone())) } Dep::Remote(remote) if remote.auto_use_tasks => { module_roots.push((remote.name.clone(), dep_path.clone())) } _ => {} }; let current_hash = match dep { Dep::Local(dep) => sha256::digest(dep.path.to_str().unwrap()), Dep::Remote(dep) => { if let Some(integrity) = &dep.integrity { sha256::digest(format!("{}{}", integrity, dep.strip_prefix)) } else { "".to_string() } } }; if dep_marker_path.exists() { let prev_hash = fs::read_to_string(&dep_marker_path).await?; if prev_hash != current_hash { if let Ok(metadata) = fs::symlink_metadata(&dep_path).await { if metadata.is_symlink() { fs::remove_file(&dep_path).await?; } else { fs::remove_dir_all(&dep_path).await?; } } } } else { // if we have no marker file and the cas_path exists, the safest thing to do is to delete the // current dep path and start over if let Ok(metadata) = fs::symlink_metadata(&dep_path).await { if metadata.is_symlink() { fs::remove_file(&dep_path).await?; } else { fs::remove_dir_all(&dep_path).await?; } } } if fs::symlink_metadata(&dep_path).await.is_err() { match dep { Dep::Local(local) => { self.link_dep(local) .await .map_err(|err| StoreError::LinkError(err))?; } Dep::Remote(dep) => { let cas_path = dep .integrity .as_ref() .map(|integrity| self.cas_path_for_integrity(integrity)); let need_fetch = match &cas_path { Some(cas_path) => !tokio::fs::try_exists(cas_path).await?, None => true, }; if need_fetch { if let Some(parent) = cas_path.as_ref().and_then(|p| p.parent()) { fs::create_dir_all(parent).await?; } let mut last_err: Option<StoreError> = None; let mut fetched = false; for (i, url) in dep.urls.iter().enumerate() { match self.fetch_dep(&client, dep, url).await { Ok(Some(computed)) => { return Err(StoreError::MissingIntegrity( dep.name.clone(), computed, )); } Ok(None) => { fetched = true; break; } Err(err) => { if dep.urls.len() > 1 && i != dep.urls.len() - 1 { eprintln!("failed to fetch `{url}`: {err}"); } last_err = Some(err); if i == dep.urls.len() - 1 { return Err(last_err.unwrap()); } } } } if !fetched { return Err(last_err.unwrap()); } } fs::create_dir_all(&dep_path).await?; self.expand_dep(dep) .await .map_err(|err| StoreError::UnpackError(err))?; } } } // write the marker once the expansion is succesful if !current_hash.is_empty() { fs::write(&dep_marker_path, current_hash).await?; } } Ok(module_roots) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/module/store.rs
crates/axl-runtime/src/module/store.rs
use anyhow::Result; use ssri::Integrity; use std::cell::RefCell; use std::collections::HashMap; use std::path::PathBuf; use std::rc::Rc; use allocative::Allocative; use derive_more::Display; use starlark::eval::Evaluator; use starlark::starlark_simple_value; use starlark::values::starlark_value; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::StarlarkValue; #[derive(Debug, ProvidesStaticType, Default)] pub struct ModuleStore { pub root_dir: PathBuf, pub module_name: String, pub module_root: PathBuf, pub deps: Rc<RefCell<HashMap<String, Dep>>>, pub tasks: Rc<RefCell<HashMap<PathBuf, (String, Vec<String>)>>>, } impl ModuleStore { pub fn new(root_dir: PathBuf, module_name: String, module_root: PathBuf) -> Self { Self { root_dir, module_name, module_root, deps: Rc::new(RefCell::new(HashMap::new())), tasks: Rc::new(RefCell::new(HashMap::new())), } } pub fn from_eval<'v>(eval: &mut Evaluator<'v, '_, '_>) -> Result<ModuleStore> { let value = eval .extra .ok_or(anyhow::anyhow!("failed to get module store"))? .downcast_ref::<ModuleStore>() .ok_or(anyhow::anyhow!("failed to cast module store"))?; Ok(ModuleStore { root_dir: value.root_dir.clone(), module_name: value.module_name.clone(), module_root: value.module_root.clone(), deps: Rc::clone(&value.deps), tasks: Rc::clone(&value.tasks), }) } } #[derive(Clone, Debug, ProvidesStaticType, Allocative)] pub enum Dep { Local(AxlLocalDep), Remote(AxlArchiveDep), } impl Dep { pub fn name(&self) -> &String { match self { Dep::Local(local) => &local.name, Dep::Remote(remote) => &remote.name, } } } #[derive(Clone, Debug, ProvidesStaticType, NoSerialize, Allocative, Display)] #[display("AxlLocalDep")] pub struct AxlLocalDep { pub name: String, pub path: PathBuf, pub auto_use_tasks: bool, } #[starlark_value(type = "AxlLocalDep")] impl<'v> StarlarkValue<'v> for AxlLocalDep {} starlark_simple_value!(AxlLocalDep); #[derive(Clone, Debug, ProvidesStaticType, NoSerialize, Allocative, Display)] #[display("AxlArchiveDep")] pub struct AxlArchiveDep { pub urls: Vec<String>, #[allocative(skip)] pub integrity: Option<Integrity>, pub dev: bool, pub name: String, pub strip_prefix: String, pub auto_use_tasks: bool, } #[starlark_value(type = "AxlArchiveDep")] impl<'v> StarlarkValue<'v> for AxlArchiveDep {} starlark_simple_value!(AxlArchiveDep);
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/module/mod.rs
crates/axl-runtime/src/module/mod.rs
mod disk_store; mod eval; mod store; pub use disk_store::{DiskStore, StoreError}; pub use eval::{ register_globals, AxlModuleEvaluator, AXL_CONFIG_EXTENSION, AXL_MODULE_FILE, AXL_ROOT_MODULE_NAME, AXL_SCRIPT_EXTENSION, }; pub use store::{AxlArchiveDep, AxlLocalDep, Dep, ModuleStore};
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/module/eval.rs
crates/axl-runtime/src/module/eval.rs
use std::fs; use std::path::PathBuf; use anyhow::Context; use anyhow::Result; use starlark::environment::Globals; use starlark::environment::GlobalsBuilder; use starlark::environment::LibraryExtension; use starlark::environment::Module; use starlark::eval::Evaluator; use starlark::starlark_module; use starlark::syntax::AstModule; use starlark::syntax::Dialect; use starlark::syntax::DialectTypes; use starlark::values; use starlark::values::list::UnpackList; use starlark::values::list_or_tuple::UnpackListOrTuple; use crate::module::AxlLocalDep; use crate::module::Dep; use super::super::eval::{validate_module_name, EvalError}; use super::store::{AxlArchiveDep, ModuleStore}; #[starlark_module] pub fn register_globals(globals: &mut GlobalsBuilder) { fn axl_dep<'v>( #[allow(unused)] #[starlark(require = named)] name: String, #[allow(unused)] #[starlark(require = named)] integrity: String, #[allow(unused)] #[starlark(require = named)] urls: UnpackList<String>, #[allow(unused)] #[starlark(require = named)] dev: bool, #[allow(unused)] #[starlark(require = named, default = false)] auto_use_tasks: bool, #[allow(unused)] #[starlark(require = named, default = String::new())] strip_prefix: String, ) -> anyhow::Result<values::none::NoneType> { Err(anyhow::anyhow!( "axl_dep has been renamed to axl_archive_dep" )) } fn local_path_override<'v>( #[allow(unused)] #[starlark(require = named)] name: String, #[allow(unused)] #[starlark(require = named)] path: String, ) -> anyhow::Result<values::none::NoneType> { Err(anyhow::anyhow!( "local_path_override has been renamed to axl_local_dep" )) } fn axl_archive_dep<'v>( #[starlark(require = named)] name: String, #[starlark(require = named, default = String::new())] integrity: String, // allow unset integrity; it is required but we'll error out later with a more helpful error message #[starlark(require = named)] urls: UnpackList<String>, #[starlark(require = named)] dev: bool, #[starlark(require = named, default = false)] auto_use_tasks: bool, #[starlark(require = named, default = String::new())] strip_prefix: String, eval: &mut Evaluator<'v, '_, '_>, ) -> anyhow::Result<values::none::NoneType> { if name == AXL_ROOT_MODULE_NAME { anyhow::bail!( "axl_archive_dep name {:?} not allowed.", AXL_ROOT_MODULE_NAME ); } validate_module_name(&name)?; if !dev { anyhow::bail!("axl_archive_dep does not support transitive dependencies yet."); } for url in &urls.items { if !url.ends_with(".tar.gz") { anyhow::bail!("only .tar.gz archives are supported at the moment.") } } let store = ModuleStore::from_eval(eval)?; let integrity = if integrity.is_empty() { None } else { Some(integrity.parse()?) }; let prev_dep = store.deps.borrow_mut().insert( name.clone(), Dep::Remote(AxlArchiveDep { name: name.clone(), strip_prefix, urls: urls.items, integrity, dev: true, auto_use_tasks, }), ); if prev_dep.is_some() { anyhow::bail!("duplicate axl dep `{}` was declared previously.", name) } Ok(values::none::NoneType) } fn axl_local_dep<'v>( #[starlark(require = named)] name: String, #[starlark(require = named)] path: String, #[starlark(require = named, default = false)] auto_use_tasks: bool, eval: &mut Evaluator<'v, '_, '_>, ) -> anyhow::Result<values::none::NoneType> { if name == AXL_ROOT_MODULE_NAME { anyhow::bail!("axl_local_dep name {:?} not allowed.", AXL_ROOT_MODULE_NAME); } validate_module_name(&name)?; let store = ModuleStore::from_eval(eval)?; let mut abs_path = PathBuf::from(path); if !abs_path.is_absolute() { abs_path = store.root_dir.join(&abs_path).canonicalize()?; } let metadata = abs_path .metadata() .context(format!("failed to stat the path {:?}", abs_path))?; if !metadata.is_dir() { anyhow::bail!("path `{:?}` is not a directory", abs_path); } let prev_dep = store.deps.borrow_mut().insert( name.clone(), Dep::Local(AxlLocalDep { name: name.clone(), path: abs_path, auto_use_tasks, }), ); if prev_dep.is_some() { anyhow::bail!("duplicate axl dep `{}` was declared previously.", name) } Ok(values::none::NoneType) } fn use_task<'v>( #[starlark(require = pos)] label: String, #[starlark(args)] symbols: UnpackListOrTuple<String>, eval: &mut Evaluator<'v, '_, '_>, ) -> anyhow::Result<values::none::NoneType> { let store = ModuleStore::from_eval(eval)?; let mut tasks = store.tasks.borrow_mut(); let absolute_path = store.module_root.join(&label); let entry = tasks.entry(absolute_path).or_insert((label, vec![])); // TODO: validate that label does not escape. entry.1.extend(symbols); Ok(values::none::NoneType) } } pub const AXL_MODULE_FILE: &str = "MODULE.aspect"; pub const AXL_ROOT_MODULE_NAME: &str = "root"; pub const AXL_SCRIPT_EXTENSION: &str = "axl"; pub const AXL_CONFIG_EXTENSION: &str = "config.axl"; /// Returns a GlobalsBuilder for MODULE.aspect specific AXL globals, extending /// various Starlark library extensions with custom top-level functions. pub fn get_globals() -> Globals { let globals = GlobalsBuilder::extended_by(&[ LibraryExtension::Breakpoint, LibraryExtension::CallStack, LibraryExtension::Debug, LibraryExtension::EnumType, LibraryExtension::Filter, LibraryExtension::Json, LibraryExtension::Map, LibraryExtension::NamespaceType, LibraryExtension::Partial, LibraryExtension::Pprint, LibraryExtension::Prepr, LibraryExtension::Print, LibraryExtension::Pstr, LibraryExtension::RecordType, LibraryExtension::SetType, LibraryExtension::StructType, LibraryExtension::Typing, ]); globals.with(register_globals).build() } /// Evaluator for MODULE.aspect #[derive(Debug)] pub struct AxlModuleEvaluator { root_dir: PathBuf, dialect: Dialect, globals: Globals, } impl AxlModuleEvaluator { pub fn new(root_dir: PathBuf) -> Self { Self { root_dir, dialect: AxlModuleEvaluator::dialect(), globals: get_globals(), } } /// Returns the configured Starlark dialect for MODULE.aspect files. fn dialect() -> Dialect { Dialect { enable_def: false, enable_lambda: false, enable_load: false, enable_load_reexport: false, enable_keyword_only_arguments: true, enable_positional_only_arguments: true, enable_types: DialectTypes::Enable, enable_f_strings: true, enable_top_level_stmt: true, ..Default::default() } } pub fn evaluate( &self, module_name: String, module_root: PathBuf, ) -> Result<ModuleStore, EvalError> { let is_root_module = module_name == AXL_ROOT_MODULE_NAME; let axl_filename = if is_root_module { AXL_MODULE_FILE.to_string() } else { module_root .join(AXL_MODULE_FILE) .to_string_lossy() .to_string() }; let module_boundary_path = &module_root.join(AXL_MODULE_FILE); let store = ModuleStore::new(self.root_dir.to_path_buf(), module_name, module_root); if module_boundary_path.exists() { let contents = fs::read_to_string(module_boundary_path)?; let ast = AstModule::parse(&axl_filename, contents, &self.dialect)?; let module = Module::new(); let mut eval = Evaluator::new(&module); eval.extra = Some(&store); eval.eval_module(ast, &self.globals)?; } Ok(store) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/store.rs
crates/axl-runtime/src/engine/store.rs
use std::path::PathBuf; use starlark::{eval::Evaluator, values::ProvidesStaticType}; use super::r#async::rt::AsyncRuntime; /// A store object which we pass to the Starlark interpreter which allows us /// to store shared data (runtime, tools, cache, ...) around the Starlark evaluation. #[derive(Debug, ProvidesStaticType, Clone)] pub struct AxlStore { pub(crate) cli_version: String, pub(crate) root_dir: PathBuf, pub(crate) script_path: PathBuf, pub(crate) rt: AsyncRuntime, } impl AxlStore { pub fn new(cli_version: String, root_dir: PathBuf, script_path: PathBuf) -> Self { Self { cli_version, root_dir: root_dir, script_path: script_path, rt: AsyncRuntime::new(), } } pub fn from_eval<'v>(eval: &mut Evaluator<'v, '_, '_>) -> anyhow::Result<AxlStore> { let value = eval .extra .as_ref() .ok_or_else(|| anyhow::anyhow!("failed to get axl store (extra is None)"))?; // Try both &AxlStore and AxlStore casts as you may get one or the other depending on how // Rust decides to compile a `eval.extra = Some(&store)` if let Some(store_ref) = value.downcast_ref::<&AxlStore>() { return Ok(AxlStore { cli_version: store_ref.cli_version.clone(), root_dir: store_ref.root_dir.clone(), script_path: store_ref.script_path.clone(), rt: store_ref.rt.clone(), }); } if let Some(store_owned) = value.downcast_ref::<AxlStore>() { return Ok(AxlStore { cli_version: store_owned.cli_version.clone(), root_dir: store_owned.root_dir.clone(), script_path: store_owned.script_path.clone(), rt: store_owned.rt.clone(), }); } Err(anyhow::anyhow!( "failed to cast axl store: unexpected type (not AxlStore nor &AxlStore). Actual type: {}", std::any::type_name_of_val(value) )) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/http.rs
crates/axl-runtime/src/engine/http.rs
use allocative::Allocative; use derive_more::Display; use futures::FutureExt; use futures::TryStreamExt; use reqwest::redirect::Policy; use starlark::environment::{Methods, MethodsBuilder, MethodsStatic}; use starlark::values::dict::UnpackDictEntries; use starlark::values::AllocValue; use starlark::values::{starlark_value, StarlarkValue}; use starlark::values::{Heap, NoSerialize, ProvidesStaticType, ValueLike}; use starlark::{starlark_module, starlark_simple_value, values}; use tokio::fs::OpenOptions; use tokio::io::AsyncWriteExt; use super::r#async::future::FutureAlloc; use super::r#async::future::StarlarkFuture; #[derive(Clone, Debug, ProvidesStaticType, NoSerialize, Allocative, Display)] #[display("<Http>")] pub struct Http { #[allocative(skip)] client: reqwest::Client, } impl Http { pub fn new() -> Self { Self { client: reqwest::Client::builder() .user_agent("AXL-Runtime") // This is the default but lets be explicit. .redirect(Policy::limited(10)) .build() .expect("failed to build the http client"), } } } #[starlark_value(type = "Http")] impl<'v> StarlarkValue<'v> for Http { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(http_methods) } } starlark_simple_value!(Http); #[starlark_module] pub(crate) fn http_methods(registry: &mut MethodsBuilder) { fn download<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = named)] url: values::StringValue, #[starlark(require = named)] output: String, #[starlark(require = named)] mode: u32, #[starlark(require = named, default = UnpackDictEntries::default())] headers: UnpackDictEntries<values::StringValue, values::StringValue>, ) -> starlark::Result<StarlarkFuture> { let client = &this.downcast_ref_err::<Http>()?.client; let mut req = client.get(url.as_str().to_string()); for (key, value) in headers.entries { req = req.header(key.as_str(), value.as_str()); } let fut = async move { let res = req.send().await?.error_for_status()?; let mut file = OpenOptions::new() .create(true) .write(true) .mode(mode) .open(output) .await?; let response = HttpResponse::from(&res); let mut stream = res.bytes_stream(); while let Some(bytes) = stream.try_next().await? { file.write_all(&bytes).await?; } Ok(response) }; Ok(StarlarkFuture::from_future::<HttpResponse>(fut)) } fn get<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = named)] url: values::StringValue, #[starlark(require = named, default = UnpackDictEntries::default())] headers: UnpackDictEntries<values::StringValue, values::StringValue>, ) -> starlark::Result<StarlarkFuture> { let client = &this.downcast_ref_err::<Http>()?.client; let mut req = client.get(url.as_str().to_string()); for (key, value) in headers.entries { req = req.header(key.as_str(), value.as_str()); } let fut = async { let res = req.send().await?; let response = HttpResponse::from_response(res).await?; Ok(response) }; Ok(StarlarkFuture::from_future(fut.boxed())) } fn post<'v>( #[allow(unused)] this: values::Value<'v>, url: values::StringValue, #[starlark(require = named, default = UnpackDictEntries::default())] headers: UnpackDictEntries<values::StringValue, values::StringValue>, data: String, ) -> starlark::Result<StarlarkFuture> { let client = &this.downcast_ref_err::<Http>()?.client; let mut req = client.post(url.as_str().to_string()); for (key, value) in headers.entries { req = req.header(key.as_str(), value.as_str()); } req = req.body(data); let fut = async { let res = req.send().await?; let response = HttpResponse::from_response(res).await?; Ok(response) }; Ok(StarlarkFuture::from_future(fut)) } } #[derive(Clone, Debug, ProvidesStaticType, NoSerialize, Allocative, Display)] #[display("<HttpResponse {status}>")] pub struct HttpResponse { status: u16, body: String, headers: Vec<(String, String)>, } impl HttpResponse { /// Creates an HttpResponse from a reqwest::Response, consuming the response /// and reading the body. pub async fn from_response(response: reqwest::Response) -> Result<Self, reqwest::Error> { let status = response.status().as_u16(); let headers: Vec<(String, String)> = response .headers() .iter() .map(|(n, v)| (n.to_string(), v.to_str().unwrap_or("").to_string())) .collect(); let body = response.text().await?; Ok(Self { status, headers, body, }) } } impl From<&reqwest::Response> for HttpResponse { fn from(value: &reqwest::Response) -> Self { Self { status: value.status().as_u16(), headers: value .headers() .iter() .map(|(n, v)| (n.to_string(), v.to_str().unwrap().to_string())) .collect(), body: String::new(), } } } #[starlark_value(type = "HttpResponse")] impl<'v> values::StarlarkValue<'v> for HttpResponse { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(http_response_methods) } } starlark_simple_value!(HttpResponse); #[starlark_module] pub(crate) fn http_response_methods(registry: &mut MethodsBuilder) { #[starlark(attribute)] fn status<'v>(this: values::Value<'v>) -> anyhow::Result<u32> { Ok(this.downcast_ref_err::<HttpResponse>()?.status as u32) } #[starlark(attribute)] fn body<'v>(this: values::Value<'v>) -> anyhow::Result<&'v str> { Ok(this.downcast_ref_err::<HttpResponse>()?.body.as_str()) } #[starlark(attribute)] fn headers<'v>(this: values::Value<'v>) -> anyhow::Result<Vec<(String, String)>> { Ok(this.downcast_ref_err::<HttpResponse>()?.headers.clone()) } } impl FutureAlloc for HttpResponse { fn alloc_value_fut<'v>(self: Box<Self>, heap: &'v Heap) -> values::Value<'v> { self.alloc_value(heap) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/task_arg.rs
crates/axl-runtime/src/engine/task_arg.rs
use std::convert::Infallible; use std::fmt::Display; use std::u32; use allocative::Allocative; use starlark::environment::GlobalsBuilder; use starlark::eval::Evaluator; use starlark::starlark_module; use starlark::starlark_simple_value; use starlark::values::list::UnpackList; use starlark::values::none::NoneOr; use starlark::values::starlark_value; use starlark::values::starlark_value_as_type::StarlarkValueAsType; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::StarlarkValue; use starlark::values::UnpackValue; use starlark::values::Value; use starlark::values::ValueLike; use starlark::ErrorKind; #[derive(Clone, Debug, ProvidesStaticType, NoSerialize, Allocative)] pub enum TaskArg { String { required: bool, default: String, }, Boolean { required: bool, default: bool, }, Int { required: bool, default: i32, }, UInt { required: bool, default: u32, }, Positional { minimum: u32, maximum: u32, default: Option<Vec<String>>, }, TrailingVarArgs, StringList { required: bool, default: Vec<String>, }, BooleanList { required: bool, default: Vec<bool>, }, IntList { required: bool, default: Vec<i32>, }, UIntList { required: bool, default: Vec<u32>, }, } /// Documentation here #[starlark_value(type = "args.TaskArg")] impl<'v> StarlarkValue<'v> for TaskArg {} starlark_simple_value!(TaskArg); impl Display for TaskArg { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::String { .. } => write!(f, "<args.TaskArg: string>"), Self::Boolean { .. } => write!(f, "<args.TaskArg: boolean>"), Self::Int { .. } => write!(f, "<args.TaskArg: int>"), Self::UInt { .. } => write!(f, "<args.TaskArg: uint>"), Self::Positional { .. } => write!(f, "<args.TaskArg: positional>"), Self::TrailingVarArgs => write!(f, "<args.TaskArg: trailing variable arguments>"), Self::StringList { .. } => write!(f, "<args.TaskArg: string_list>"), Self::BooleanList { .. } => write!(f, "<args.TaskArg: boolean_list>"), Self::IntList { .. } => write!(f, "<args.TaskArg: int_list>"), Self::UIntList { .. } => write!(f, "<args.TaskArg: uint_list>"), } } } impl<'v> UnpackValue<'v> for TaskArg { type Error = Infallible; fn unpack_value_impl(value: Value<'v>) -> Result<Option<Self>, Self::Error> { Ok(value.downcast_ref::<Self>().map(|value| value.clone())) } } #[starlark_module] pub fn register_globals(globals: &mut GlobalsBuilder) { const Args: StarlarkValueAsType<TaskArg> = StarlarkValueAsType::new(); /// Defines a positional argument that accepts a range of values, with a required minimum /// number of values and an optional maximum number of values. /// /// /// **Examples** /// ```python /// **Take** one positional argument with no dashes. /// task( /// args = { "named": args.positional() } /// ) /// ``` /// /// ```python /// **Take** two positional argument with no dashes. /// task( /// args = { "named": args.positional(minimum = 2, maximum = 2) } /// ) /// ``` fn positional<'v>( #[starlark(require = named, default = 0)] minimum: u32, #[starlark(require = named, default = 1)] maximum: u32, #[starlark(require = named, default = NoneOr::None)] default: NoneOr<UnpackList<String>>, ) -> starlark::Result<TaskArg> { Ok(TaskArg::Positional { minimum: minimum, maximum: maximum, default: default.into_option().map(|it| it.items), }) } /// Defines a trailing variable argument that captures the remaining arguments without further parsing. /// Only one such argument is permitted, and it must be the last in the sequence. /// /// **Examples** /// ```python /// task( /// args = { /// # take one positional argument with no dashes. /// "target": args.positional(minimum = 0, maximum = 1), /// # take rest of the commandline /// "run_args": args.trailing_var_args() /// } /// ) /// ``` fn trailing_var_args<'v>() -> starlark::Result<TaskArg> { Ok(TaskArg::TrailingVarArgs {}) } /// Defines a string flag that can be specified as `--flag_name=flag_value`. /// /// **Examples** /// ```python /// task( /// args = { /// "bes_backend": args.string(), /// } /// ) /// ``` fn string<'v>( #[starlark(require = named, default = false)] required: bool, #[starlark(require = named)] default: Option<String>, ) -> starlark::Result<TaskArg> { if required && default.is_some() { return Err(starlark::Error::new_kind(ErrorKind::Function( anyhow::anyhow!("`required` and `default` are both set."), ))); } Ok(TaskArg::String { required, default: default.unwrap_or_default(), }) } /// Defines a string list flag that can be specified multiple times as `--flag_name=flag_value`. /// /// **Examples** /// ```python /// task( /// args = { /// "bes_headers": args.string_list(), /// } /// ) /// ``` fn string_list<'v>( #[starlark(require = named, default = false)] required: bool, #[starlark(require = named, default = NoneOr::None)] default: NoneOr<UnpackList<String>>, ) -> starlark::Result<TaskArg> { if required && !default.is_none() { return Err(starlark::Error::new_kind(ErrorKind::Function( anyhow::anyhow!("`required` and `default` are both set."), ))); } Ok(TaskArg::StringList { required, default: default.into_option().map(|it| it.items).unwrap_or_default(), }) } /// Defines a boolean flag that can be specified as `--flag_name=true|false` /// or simply `--flag_name`, which is equivalent to `--flag_name=true`. /// /// **Examples** /// ```python /// task( /// args = { /// "color": args.boolean(), /// } /// ) /// ``` fn boolean<'v>( #[starlark(require = named, default = false)] required: bool, #[starlark(require = named )] default: Option<bool>, _eval: &mut Evaluator<'v, '_, '_>, ) -> starlark::Result<TaskArg> { if required && default.is_some() { return Err(starlark::Error::new_kind(ErrorKind::Function( anyhow::anyhow!("`required` and `default` are both set."), ))); } Ok(TaskArg::Boolean { required, default: default.unwrap_or_default(), }) } /// Defines a boolean list flag that can be specified multiple times as `--flag_name=true|false`. /// /// **Examples** /// ```python /// task( /// args = { /// "flags": args.boolean_list(), /// } /// ) /// ``` fn boolean_list<'v>( #[starlark(require = named, default = false)] required: bool, #[starlark(require = named, default = NoneOr::None)] default: NoneOr<UnpackList<bool>>, ) -> starlark::Result<TaskArg> { if required && !default.is_none() { return Err(starlark::Error::new_kind(ErrorKind::Function( anyhow::anyhow!("`required` and `default` are both set."), ))); } Ok(TaskArg::BooleanList { required, default: default.into_option().map(|it| it.items).unwrap_or_default(), }) } /// Creates an integer flag that can be set as `--flag_name=flag_value` /// or `--flag_name=flag_value`. /// /// **Examples** /// ```python /// task( /// args = { /// "color": args.int(), /// } /// ) /// ``` fn int<'v>( #[starlark(require = named, default = false)] required: bool, #[starlark(require = named)] default: Option<i32>, ) -> starlark::Result<TaskArg> { if required && default.is_some() { return Err(starlark::Error::new_kind(ErrorKind::Function( anyhow::anyhow!("`required` and `default` are both set."), ))); } Ok(TaskArg::Int { required, default: default.unwrap_or_default(), }) } /// Defines an integer list flag that can be specified multiple times as `--flag_name=flag_value`. /// /// **Examples** /// ```python /// task( /// args = { /// "numbers": args.int_list(), /// } /// ) /// ``` fn int_list<'v>( #[starlark(require = named, default = false)] required: bool, #[starlark(require = named, default = NoneOr::None)] default: NoneOr<UnpackList<i32>>, ) -> starlark::Result<TaskArg> { if required && !default.is_none() { return Err(starlark::Error::new_kind(ErrorKind::Function( anyhow::anyhow!("`required` and `default` are both set."), ))); } Ok(TaskArg::IntList { required, default: default.into_option().map(|it| it.items).unwrap_or_default(), }) } /// Defines an unsigned integer flag that can be specified using the format `--flag_name=flag_value`. /// /// **Examples** /// ```python /// task( /// args = { /// "color": args.uint(), /// } /// ) /// ``` fn uint<'v>( #[starlark(require = named, default = false)] required: bool, #[starlark(require = named)] default: Option<u32>, ) -> starlark::Result<TaskArg> { if required && default.is_some() { return Err(starlark::Error::new_kind(ErrorKind::Function( anyhow::anyhow!("`required` and `default` are both set."), ))); } Ok(TaskArg::UInt { required, default: default.unwrap_or_default(), }) } /// Defines an unsigned integer list flag that can be specified multiple times as `--flag_name=flag_value`. /// /// **Examples** /// ```python /// task( /// args = { /// "ports": args.uint_list(), /// } /// ) /// ``` fn uint_list<'v>( #[starlark(require = named, default = false)] required: bool, #[starlark(require = named, default = NoneOr::None)] default: NoneOr<UnpackList<u32>>, ) -> starlark::Result<TaskArg> { if required && !default.is_none() { return Err(starlark::Error::new_kind(ErrorKind::Function( anyhow::anyhow!("`required` and `default` are both set."), ))); } Ok(TaskArg::UIntList { required, default: default.into_option().map(|it| it.items).unwrap_or_default(), }) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/task_context.rs
crates/axl-runtime/src/engine/task_context.rs
use allocative::Allocative; use derive_more::Display; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::starlark_module; use starlark::starlark_simple_value; use starlark::values; use starlark::values::starlark_value; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::Trace; use starlark::values::ValueLike; use super::bazel::Bazel; use super::http::Http; use super::std::Std; use super::task_args::FrozenTaskArgs; use super::task_args::TaskArgs; use super::template; use super::wasm::Wasm; #[derive(Debug, Clone, ProvidesStaticType, Display, Trace, NoSerialize, Allocative)] #[display("<TaskContext>")] pub struct TaskContext<'v> { pub args: TaskArgs<'v>, pub config: values::Value<'v>, } impl<'v> TaskContext<'v> { pub fn new(args: TaskArgs<'v>, config: values::Value<'v>) -> Self { Self { args, config } } } #[starlark_value(type = "TaskContext")] impl<'v> values::StarlarkValue<'v> for TaskContext<'v> { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(task_context_methods) } } impl<'v> values::AllocValue<'v> for TaskContext<'v> { fn alloc_value(self, heap: &'v values::Heap) -> values::Value<'v> { heap.alloc_complex(self) } } impl<'v> values::Freeze for TaskContext<'v> { type Frozen = FrozenTaskContext; fn freeze(self, _freezer: &values::Freezer) -> values::FreezeResult<Self::Frozen> { panic!("not implemented") } } #[derive(Debug, Display, ProvidesStaticType, NoSerialize, Allocative)] #[display("<TaskContext>")] pub struct FrozenTaskContext { #[allocative(skip)] args: FrozenTaskArgs, #[allocative(skip)] config: values::FrozenValue, } starlark_simple_value!(FrozenTaskContext); #[starlark_value(type = "TaskContext")] impl<'v> values::StarlarkValue<'v> for FrozenTaskContext { type Canonical = TaskContext<'v>; } #[starlark_module] pub(crate) fn task_context_methods(registry: &mut MethodsBuilder) { /// Standard library is the foundation of powerful AXL tasks. #[starlark(attribute)] fn std<'v>(#[allow(unused)] this: values::Value<'v>) -> starlark::Result<Std> { Ok(Std {}) } /// Access to arguments provided by the caller. #[starlark(attribute)] fn args<'v>(#[allow(unused)] this: values::Value<'v>) -> starlark::Result<TaskArgs<'v>> { let ctx = this.downcast_ref_err::<TaskContext>()?; // TODO: don't do this. Ok(ctx.args.clone()) } /// Access to the task configuration. #[starlark(attribute)] fn config<'v>(this: values::Value<'v>) -> starlark::Result<values::Value<'v>> { let ctx = this.downcast_ref_err::<TaskContext>()?; Ok(ctx.config) } /// Expand template files. #[starlark(attribute)] fn template<'v>( #[allow(unused)] this: values::Value<'v>, ) -> starlark::Result<template::Template> { Ok(template::Template::new()) } /// EXPERIMENTAL! Run wasm programs within tasks. #[starlark(attribute)] fn wasm<'v>(#[allow(unused)] this: values::Value<'v>) -> starlark::Result<Wasm> { Ok(Wasm::new()) } /// Access to Bazel functionality. #[starlark(attribute)] fn bazel<'v>(#[allow(unused)] this: values::Value<'v>) -> starlark::Result<Bazel> { Ok(Bazel {}) } /// The `http` attribute provides a programmatic interface for making HTTP requests. /// It is used to fetch data from remote servers and can be used in conjunction with /// other aspects to perform complex data processing tasks. /// /// **Example** /// /// ```starlark /// **Fetch** data from a remote server /// data = ctx.http().get("https://example.com/data.json").block() /// ``` fn http<'v>(#[allow(unused)] this: values::Value<'v>) -> starlark::Result<Http> { Ok(Http::new()) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/mod.rs
crates/axl-runtime/src/engine/mod.rs
use starlark::{ environment::GlobalsBuilder, starlark_module, values::starlark_value_as_type::StarlarkValueAsType, }; mod bazel; mod globals; mod http; mod std; mod template; mod types; mod wasm; pub mod r#async; pub mod config; pub mod store; pub mod task; pub mod task_arg; pub mod task_args; pub mod task_context; #[starlark_module] fn register_types(globals: &mut GlobalsBuilder) { const ConfigContext: StarlarkValueAsType<config::ConfigContext> = StarlarkValueAsType::new(); const Http: StarlarkValueAsType<http::Http> = StarlarkValueAsType::new(); const HttpResponse: StarlarkValueAsType<http::HttpResponse> = StarlarkValueAsType::new(); const Task: StarlarkValueAsType<task::Task> = StarlarkValueAsType::new(); const TaskArg: StarlarkValueAsType<task_arg::TaskArg> = StarlarkValueAsType::new(); const TaskArgs: StarlarkValueAsType<task_args::TaskArgs> = StarlarkValueAsType::new(); const TaskContext: StarlarkValueAsType<task_context::TaskContext> = StarlarkValueAsType::new(); const Template: StarlarkValueAsType<template::Template> = StarlarkValueAsType::new(); } #[starlark_module] fn register_wasm_types(globals: &mut GlobalsBuilder) { const Wasm: StarlarkValueAsType<wasm::Wasm> = StarlarkValueAsType::new(); const WasmCallable: StarlarkValueAsType<wasm::WasmCallable> = StarlarkValueAsType::new(); const WasmExports: StarlarkValueAsType<wasm::WasmExports> = StarlarkValueAsType::new(); const WasmInstance: StarlarkValueAsType<wasm::WasmInstance> = StarlarkValueAsType::new(); const WasmMemory: StarlarkValueAsType<wasm::WasmMemory> = StarlarkValueAsType::new(); } pub fn register_globals(globals: &mut GlobalsBuilder) { register_types(globals); globals::register_globals(globals); r#async::register_globals(globals); task::register_globals(globals); globals.namespace("args", task_arg::register_globals); globals.namespace("bazel", bazel::register_globals); globals.namespace("std", std::register_globals); globals.namespace("wasm", register_wasm_types); }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/task.rs
crates/axl-runtime/src/engine/task.rs
use crate::engine::task_context::TaskContext; use super::task_arg::TaskArg; use allocative::Allocative; use derive_more::Display; use starlark::collections::SmallMap; use starlark::environment::GlobalsBuilder; use starlark::starlark_module; use starlark::starlark_simple_value; use starlark::typing::ParamIsRequired; use starlark::typing::ParamSpec; use starlark::values; use starlark::values::list::UnpackList; use starlark::values::none::NoneOr; use starlark::values::none::NoneType; use starlark::values::starlark_value; use starlark::values::typing::StarlarkCallableParamSpec; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::StarlarkValue; use starlark::values::Trace; use starlark::values::Value; pub const MAX_TASK_GROUPS: usize = 5; pub trait TaskLike<'v>: 'v { fn args(&self) -> &SmallMap<String, TaskArg>; fn description(&self) -> &String; fn group(&self) -> &Vec<String>; fn name(&self) -> &String; } pub trait AsTaskLike<'v>: TaskLike<'v> { fn as_task(&self) -> &dyn TaskLike<'v>; } impl<'v, T> AsTaskLike<'v> for T where T: TaskLike<'v>, { fn as_task(&self) -> &dyn TaskLike<'v> { self } } #[derive(Debug, Clone, ProvidesStaticType, Display, Trace, NoSerialize, Allocative)] #[display("<Task>")] pub struct Task<'v> { r#impl: values::Value<'v>, #[allocative(skip)] pub(super) args: SmallMap<String, TaskArg>, pub(super) description: String, pub(super) group: Vec<String>, pub(super) name: String, pub(super) config: values::Value<'v>, } impl<'v> Task<'v> { pub fn implementation(&self) -> values::Value<'v> { self.r#impl } pub fn args(&self) -> &SmallMap<String, TaskArg> { &self.args } pub fn description(&self) -> &String { &self.description } pub fn group(&self) -> &Vec<String> { &self.group } pub fn name(&self) -> &String { &self.name } pub fn config(&self) -> values::Value<'v> { self.config } } impl<'v> TaskLike<'v> for Task<'v> { fn args(&self) -> &SmallMap<String, TaskArg> { &self.args } fn description(&self) -> &String { &self.description } fn group(&self) -> &Vec<String> { &self.group } fn name(&self) -> &String { &self.name } } #[starlark_value(type = "Task")] impl<'v> StarlarkValue<'v> for Task<'v> {} impl<'v> values::AllocValue<'v> for Task<'v> { fn alloc_value(self, heap: &'v values::Heap) -> Value<'v> { heap.alloc_complex(self) } } impl<'v> values::Freeze for Task<'v> { type Frozen = FrozenTask; fn freeze(self, freezer: &values::Freezer) -> values::FreezeResult<Self::Frozen> { let frozen_impl = self.r#impl.freeze(freezer)?; let frozen_config = self.config.freeze(freezer)?; Ok(FrozenTask { args: self.args, r#impl: frozen_impl, description: self.description, group: self.group, name: self.name, config: frozen_config, }) } } #[derive(Debug, Display, Clone, ProvidesStaticType, Trace, NoSerialize, Allocative)] #[display("<Task>")] pub struct FrozenTask { r#impl: values::FrozenValue, #[allocative(skip)] pub(super) args: SmallMap<String, TaskArg>, pub(super) description: String, pub(super) group: Vec<String>, pub(super) name: String, pub(super) config: values::FrozenValue, } starlark_simple_value!(FrozenTask); #[starlark_value(type = "Task")] impl<'v> StarlarkValue<'v> for FrozenTask { type Canonical = Task<'v>; } impl FrozenTask { pub fn implementation(&self) -> values::FrozenValue { self.r#impl } pub fn config(&self) -> values::FrozenValue { self.config } } impl<'v> TaskLike<'v> for FrozenTask { fn args(&self) -> &SmallMap<String, TaskArg> { &self.args } fn description(&self) -> &String { &self.description } fn group(&self) -> &Vec<String> { &self.group } fn name(&self) -> &String { &self.name } } struct TaskImpl; impl StarlarkCallableParamSpec for TaskImpl { fn params() -> ParamSpec { ParamSpec::new_parts( [(ParamIsRequired::Yes, TaskContext::get_type_starlark_repr())], [], None, [], None, ) .unwrap() } } #[starlark_module] pub fn register_globals(globals: &mut GlobalsBuilder) { /// Task type representing a Task. /// /// ```python /// def _task_impl(ctx): /// pass /// /// build = task( /// name = "build", /// group = [], /// impl = _task_impl, /// description = "build task", /// task_args = { /// "target": args.string(), /// }, /// config = None # Optional user-defined config (e.g., a record); defaults to None if not provided /// ) /// ``` fn task<'v>( #[starlark(require = named)] implementation: values::typing::StarlarkCallable< 'v, TaskImpl, NoneType, >, #[starlark(require = named)] args: values::dict::UnpackDictEntries<&'v str, TaskArg>, #[starlark(require = named, default = String::new())] description: String, #[starlark(require = named, default = UnpackList::default())] group: UnpackList<String>, #[starlark(require = named, default = String::new())] name: String, #[starlark(require = named, default = NoneOr::None)] config: NoneOr<values::Value<'v>>, ) -> starlark::Result<Task<'v>> { if group.items.len() > MAX_TASK_GROUPS { return Err(anyhow::anyhow!( "task cannot have more than {} group levels", MAX_TASK_GROUPS ) .into()); } let mut args_ = SmallMap::new(); for (arg, def) in args.entries { args_.insert(arg.to_owned(), def.clone()); } Ok(Task { args: args_, r#impl: implementation.0, description, group: group.items, name, config: config.into_option().unwrap_or(values::Value::new_none()), }) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/task_args.rs
crates/axl-runtime/src/engine/task_args.rs
use allocative::Allocative; use derive_more::Display; use starlark::collections::SmallMap; use starlark::starlark_simple_value; use starlark::values; use starlark::values::list::AllocList; use starlark::values::starlark_value; use starlark::values::Heap; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::StarlarkValue; use starlark::values::Trace; use starlark::values::Value; #[derive(Debug, Clone, ProvidesStaticType, Display, Trace, NoSerialize, Allocative)] #[display("<TaskArgs>")] pub struct TaskArgs<'v> { #[allocative(skip)] args: SmallMap<String, values::Value<'v>>, } impl<'v> TaskArgs<'v> { pub fn new() -> Self { Self { args: SmallMap::new(), } } #[inline] pub fn insert(&mut self, key: String, value: values::Value<'v>) { self.args.insert(key, value); } #[inline] pub fn alloc_list<L>(items: L) -> AllocList<L> { AllocList(items) } } #[starlark_value(type = "TaskArgs")] impl<'v> StarlarkValue<'v> for TaskArgs<'v> { fn get_attr(&self, key: &str, _heap: &'v Heap) -> Option<Value<'v>> { self.args.get(key).cloned() } } impl<'v> values::AllocValue<'v> for TaskArgs<'v> { fn alloc_value(self, heap: &'v values::Heap) -> Value<'v> { heap.alloc_complex(self) } } impl<'v> values::Freeze for TaskArgs<'v> { type Frozen = FrozenTaskArgs; fn freeze(self, freezer: &values::Freezer) -> values::FreezeResult<Self::Frozen> { Ok(FrozenTaskArgs { args: self .args .iter() .map(|(k, v)| (k.clone(), v.freeze(freezer).unwrap())) .collect(), }) } } #[derive(Debug, Display, ProvidesStaticType, NoSerialize, Allocative)] #[display("<TaskArgs {args:?}>")] pub struct FrozenTaskArgs { #[allocative(skip)] args: SmallMap<String, values::FrozenValue>, } starlark_simple_value!(FrozenTaskArgs); #[starlark_value(type = "TaskArgs")] impl<'v> StarlarkValue<'v> for FrozenTaskArgs { type Canonical = TaskArgs<'v>; }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/wasm.rs
crates/axl-runtime/src/engine/wasm.rs
use allocative::Allocative; use anyhow::Context; use derive_more::Display; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::eval::Arguments; use starlark::eval::Evaluator; use starlark::values::dict::UnpackDictEntries; use starlark::values::list::UnpackList; use starlark::values::none::NoneType; use starlark::values::tuple::AllocTuple; use starlark::values::tuple::UnpackTuple; use starlark::values::AllocValue; use starlark::values::Heap; use starlark::values::Value; use starlark::values::ValueLike; use starlark::StarlarkResultExt; use starlark_derive::Trace; use wasmi_wasi::ambient_authority; use std::cell::RefCell; use std::fmt::Debug; use std::rc::Rc; use wasmi::AsContext; use wasmi::AsContextMut; use wasmi_wasi::WasiCtx; use starlark::starlark_module; use starlark::starlark_simple_value; use starlark::values; use starlark::values::starlark_value; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use crate::engine::types::bytes::Bytes; #[derive(Display, Trace, ProvidesStaticType, NoSerialize, Allocative)] #[display("<wasm.WasmMemory>")] pub struct WasmMemory { #[allocative(skip)] store: Rc<RefCell<wasmi::Store<WasiCtx>>>, #[allocative(skip)] memory: Rc<RefCell<wasmi::Memory>>, } impl Debug for WasmMemory { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("wasm.WasmMemory") .field("memory", &self.memory) .finish() } } #[starlark_value(type = "wasm.WasmMemory")] impl<'v> values::StarlarkValue<'v> for WasmMemory { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(wasm_memory_methods) } } #[starlark_module] pub(crate) fn wasm_memory_methods(registry: &mut MethodsBuilder) { fn grow<'v>( this: values::Value<'v>, #[starlark(require = pos)] by: u64, ) -> anyhow::Result<u64> { let wm = this.downcast_ref::<WasmMemory>().unwrap(); let mem = wm.memory.borrow(); let pages = mem.grow(wm.store.borrow_mut().as_context_mut(), by)?; Ok(pages) } fn write<'v>( this: values::Value<'v>, #[starlark(require = pos)] offset: usize, #[starlark(require = pos)] buffer: Value<'v>, heap: &'v values::Heap, ) -> anyhow::Result<NoneType> { let wm = this.downcast_ref::<WasmMemory>().unwrap(); let mem = wm.memory.borrow(); let iter = buffer .iterate(heap) .into_anyhow_result() .context("buffer is not iterable")?; mem.write( wm.store.borrow_mut().as_context_mut(), offset, iter.map(|x| x.unpack_i32().expect("invalid integer") as u8) .collect::<Vec<u8>>() .as_slice(), )?; Ok(NoneType) } /// Reads bytes from wasm linear memory. /// /// # Arguments /// * `offset` - The byte offset in wasm memory to start reading from /// * `length` - The number of bytes to read /// /// # Returns /// A `Bytes` object containing the data read from memory. /// /// # Example /// ```starlark /// # Get pointer and length from a wasm function /// result = wasm_instance.exports.get_data() /// ptr = result & 0xFFFFFFFF /// length = (result >> 32) & 0xFFFFFFFF /// /// # Read the data from wasm memory /// data = memory.read(ptr, length) /// print(str(data)) /// ``` fn read<'v>( this: values::Value<'v>, #[starlark(require = pos)] offset: usize, #[starlark(require = pos)] length: usize, ) -> anyhow::Result<Bytes> { let wm = this.downcast_ref::<WasmMemory>().unwrap(); let mem = wm.memory.borrow(); let mut buffer = vec![0u8; length]; mem.read(wm.store.borrow_mut().as_context_mut(), offset, &mut buffer)?; Ok(Bytes::from(buffer.as_slice())) } } impl<'v> AllocValue<'v> for WasmMemory { fn alloc_value(self, heap: &'v values::Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } } #[derive(Display, Trace, ProvidesStaticType, NoSerialize, Allocative)] #[display("<wasm.WasmCallable>")] pub struct WasmCallable { name: String, #[allocative(skip)] store: Rc<RefCell<wasmi::Store<WasiCtx>>>, #[allocative(skip)] instance: Rc<RefCell<wasmi::Instance>>, } impl Debug for WasmCallable { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("wasm.WasmCallable") .field("instance", &self.instance) .finish() } } #[starlark_value(type = "wasm.WasmCallable")] impl<'v> values::StarlarkValue<'v> for WasmCallable { fn invoke( &self, _me: Value<'v>, args: &Arguments<'v, '_>, eval: &mut Evaluator<'v, '_, '_>, ) -> starlark::Result<Value<'v>> { let mut store = self.store.borrow_mut(); let instance = self.instance.borrow_mut(); let func = instance .get_func(store.as_context_mut(), &self.name) .context(format!("module does not export function `{}`", &self.name))?; let ty = func.ty(store.as_context_mut()); let mut inputs: Vec<wasmi::Val> = vec![]; let mut outputs: Vec<wasmi::Val> = vec![]; let heap = eval.heap(); let positionals = if !ty.params().is_empty() { use starlark::__derive_refs::{ parse_args::{check_required, parse_signature}, sig::parameter_spec, }; let __args: [_; 1] = parse_signature( &parameter_spec("args", &[], &[], true, &[], false), args, eval.heap(), )?; let positionals: UnpackTuple<Value<'v>> = check_required("args", __args[0])?; positionals.items } else { vec![] }; if positionals.len() != ty.params().len() { return Err(starlark::Error::new_kind(starlark::ErrorKind::Function( anyhow::anyhow!( "expected {} arguments, got {}", ty.params().len(), positionals.len(), ), ))); } for (idx, param) in ty.params().iter().enumerate() { let arg = positionals[idx]; match param { wasmi::ValType::I32 => inputs .push(wasmi::Val::I32(arg.unpack_i32().ok_or(anyhow::anyhow!( "argument {idx} should be an integer" ))?)), wasmi::ValType::I64 => inputs.push(wasmi::Val::I64( arg.unpack_i32() .ok_or(anyhow::anyhow!("argument {idx} should be an integer"))? as i64, )), wasmi::ValType::F64 => inputs.push(wasmi::Val::F64(wasmi::F64::from_float( arg.unpack_i32() .ok_or(anyhow::anyhow!("argument {idx} should be a float"))? as f64, ))), wasmi::ValType::F32 => inputs.push(wasmi::Val::F32(wasmi::F32::from_float( arg.unpack_i32() .ok_or(anyhow::anyhow!("argument {idx} should be a float"))? as f32, ))), wasmi::ValType::V128 => todo!("Implement support for 128-bit values"), wasmi::ValType::FuncRef => todo!("Implement support for function references"), wasmi::ValType::ExternRef => todo!("Implement support for external references"), } } for param in ty.results().iter() { match param { wasmi::ValType::I32 => outputs.push(wasmi::Val::I32(0)), wasmi::ValType::I64 => outputs.push(wasmi::Val::I64(0)), wasmi::ValType::F32 => outputs.push(wasmi::Val::F32(wasmi::F32::from_float(0.0))), wasmi::ValType::F64 => outputs.push(wasmi::Val::F64(wasmi::F64::from_float(0.0))), wasmi::ValType::V128 => todo!("Implement support for 128-bit values"), wasmi::ValType::FuncRef => todo!("Implement support for function references"), wasmi::ValType::ExternRef => todo!("Implement support for external references"), } } func.call(store.as_context_mut(), &inputs, &mut outputs) .expect("failed to call"); let wrap_val = |x: wasmi::Val| match x { wasmi::Val::I32(v) => heap.alloc(v), wasmi::Val::I64(v) => heap.alloc(v), wasmi::Val::F32(v) => heap.alloc(v.to_float() as f64), wasmi::Val::F64(v) => heap.alloc(v.to_float()), wasmi::Val::V128(_v) => todo!("Implement support for 128-bit values"), wasmi::Val::FuncRef(_v) => todo!("Implement support for function references"), wasmi::Val::ExternRef(_v) => todo!("Implement support for external references"), }; if outputs.is_empty() { return Ok(Value::new_none()); } else if outputs.len() == 1 { return Ok(wrap_val(outputs.pop().unwrap())); } Ok(heap.alloc(AllocTuple(outputs.into_iter().map(wrap_val)))) } } impl<'v> AllocValue<'v> for WasmCallable { fn alloc_value(self, heap: &'v values::Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } } #[derive(Display, Trace, ProvidesStaticType, NoSerialize, Allocative)] #[display("<warm.WasmExports>")] pub struct WasmExports { #[allocative(skip)] module: Rc<RefCell<wasmi::Module>>, #[allocative(skip)] store: Rc<RefCell<wasmi::Store<WasiCtx>>>, #[allocative(skip)] instance: Rc<RefCell<wasmi::Instance>>, } impl Debug for WasmExports { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("wasm.WasmExports") .field("module", &self.module) .field("instance", &self.instance) .finish() } } #[starlark_value(type = "wasm.WasmExports")] impl<'v> values::StarlarkValue<'v> for WasmExports { fn get_attr(&self, _attribute: &str, heap: &'v Heap) -> Option<Value<'v>> { Some(heap.alloc(WasmCallable { name: _attribute.to_string(), instance: Rc::clone(&self.instance), store: Rc::clone(&self.store), })) } } impl<'v> AllocValue<'v> for WasmExports { fn alloc_value(self, heap: &'v values::Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } } #[derive(Display, Trace, ProvidesStaticType, NoSerialize, Allocative)] #[display("<wasm.WasmInstance>")] pub struct WasmInstance { #[allocative(skip)] module: Rc<RefCell<wasmi::Module>>, #[allocative(skip)] store: Rc<RefCell<wasmi::Store<WasiCtx>>>, #[allocative(skip)] instance: Rc<RefCell<wasmi::Instance>>, } impl Debug for WasmInstance { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("wasm.WasmInstance") .field("module", &self.module) .field("instance", &self.instance) .finish() } } #[starlark_value(type = "wasm.WasmInstance")] impl<'v> values::StarlarkValue<'v> for WasmInstance { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(wasm_instance_methods) } } impl<'v> AllocValue<'v> for WasmInstance { fn alloc_value(self, heap: &'v values::Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } } #[starlark_module] pub(crate) fn wasm_instance_methods(registry: &mut MethodsBuilder) { fn get_memory<'v>( this: values::Value<'v>, #[starlark(require = pos)] name: values::StringValue, ) -> anyhow::Result<WasmMemory> { let wi = this.downcast_ref::<WasmInstance>().unwrap(); let mut store = wi.store.borrow_mut(); let memory = wi .instance .borrow() .get_memory(store.as_context_mut(), name.as_str()) .unwrap(); Ok(WasmMemory { store: Rc::clone(&wi.store), memory: Rc::new(RefCell::new(memory)), }) } #[starlark(attribute)] fn exports<'v>(this: values::Value<'v>) -> anyhow::Result<WasmExports> { let wi = this.downcast_ref::<WasmInstance>().unwrap(); Ok(WasmExports { module: Rc::clone(&wi.module), store: Rc::clone(&wi.store), instance: Rc::clone(&wi.instance), }) } fn start<'v>(this: values::Value<'v>) -> anyhow::Result<bool> { let wi = this.downcast_ref::<WasmInstance>().unwrap(); let mut store = wi.store.borrow_mut(); let instance = wi.instance.borrow_mut(); let func = instance.get_func(store.as_context(), "_start").unwrap(); let inputs: Vec<wasmi::Val> = vec![]; let mut outputs: Vec<wasmi::Val> = vec![]; let _ = func.call(store.as_context_mut(), &inputs, &mut outputs); Ok(true) } } #[derive(Debug, Display, ProvidesStaticType, NoSerialize, Allocative)] #[display("<wasm.Wasm>")] pub struct Wasm {} impl Wasm { pub fn new() -> Self { Self {} } } #[starlark_value(type = "wasm.Wasm")] impl<'v> values::StarlarkValue<'v> for Wasm { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(wasm_methods) } } starlark_simple_value!(Wasm); #[starlark_module] pub(crate) fn wasm_methods(registry: &mut MethodsBuilder) { fn instantiate<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, #[starlark(require = named, default = UnpackList::default())] args: UnpackList<String>, #[starlark(require = named, default = UnpackDictEntries::default())] env: UnpackDictEntries< String, values::StringValue, >, #[starlark(require = named, default = UnpackDictEntries::default())] preopened_dirs: UnpackDictEntries<values::StringValue, values::StringValue>, #[starlark(require = named, default = true)] inherit_stdio: bool, ) -> anyhow::Result<WasmInstance> { let mut wasi = wasmi_wasi::WasiCtxBuilder::new(); if inherit_stdio { wasi.inherit_stdio(); } for arg in args.items { wasi.arg(arg.as_str())?; } for (key, value) in env.entries { wasi.env(key.as_str(), value.as_str())?; } for (key, value) in preopened_dirs.entries { wasi.preopened_dir( wasmi_wasi::Dir::open_ambient_dir(key.as_str(), ambient_authority())?, value.as_str(), )?; } let wasi = wasi.build(); let mut config = wasmi::Config::default(); config.compilation_mode(wasmi::CompilationMode::Eager); let mut store = wasmi::Store::new(&wasmi::Engine::new(&config), wasi); let bytes = std::fs::read(path.as_str()) .context("failed to read wasm binary at path {path.as_str()}")?; let module = wasmi::Module::new(store.engine(), bytes)?; let mut linker = <wasmi::Linker<WasiCtx>>::new(store.engine()); wasmi_wasi::add_to_linker(&mut linker, |ctx| ctx)?; let instance = linker.instantiate_and_start(&mut store, &module)?; Ok(WasmInstance { module: Rc::new(RefCell::new(module)), store: Rc::new(RefCell::new(store)), instance: Rc::new(RefCell::new(instance)), }) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/globals/mod.rs
crates/axl-runtime/src/engine/globals/mod.rs
use allocative::Allocative; use derive_more::Display; use starlark::environment::GlobalsBuilder; use starlark::starlark_module; use starlark::starlark_simple_value; use starlark::values; use starlark::values::starlark_value; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::Trace; use std::fmt::Debug; use std::sync::atomic::AtomicU64; use std::sync::atomic::Ordering; use std::thread::sleep; use std::time::Duration; use starlark::typing::Ty; use starlark::values::Heap; #[derive(ProvidesStaticType, Display, Trace, NoSerialize, Allocative, Debug)] #[display("<ClockIterator>")] struct ClockIterator { rate: u64, counter: AtomicU64, } starlark_simple_value!(ClockIterator); #[starlark_value(type = "ClockIterator")] impl<'v> values::StarlarkValue<'v> for ClockIterator { fn eval_type(&self) -> Option<Ty> { Some(Ty::iter( axl_proto::tools::protos::ExecLogEntry::get_type_starlark_repr(), )) } fn get_type_starlark_repr() -> Ty { Ty::iter(axl_proto::tools::protos::ExecLogEntry::get_type_starlark_repr()) } unsafe fn iterate( &self, me: values::Value<'v>, _heap: &'v Heap, ) -> starlark::Result<values::Value<'v>> { Ok(me) } unsafe fn iter_next(&self, _index: usize, heap: &'v Heap) -> Option<values::Value<'v>> { sleep(Duration::from_millis(self.rate)); Some(heap.alloc(self.counter.fetch_add(1, Ordering::Relaxed))) } unsafe fn iter_stop(&self) {} } #[starlark_module] pub fn register_globals(globals: &mut GlobalsBuilder) { /// Forever clock iterator fn forever<'v>(#[starlark()] rate: u32) -> starlark::Result<ClockIterator> { Ok(ClockIterator { rate: rate as u64, counter: AtomicU64::new(0), }) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/async/future.rs
crates/axl-runtime/src/engine/async/future.rs
use allocative::Allocative; use derive_more::Display; use futures::future::BoxFuture; use futures::FutureExt; use starlark::environment::{Methods, MethodsBuilder, MethodsStatic}; use starlark::eval::Evaluator; use starlark::starlark_module; use starlark::typing::Ty; use starlark::values::type_repr::StarlarkTypeRepr; use starlark::values::{self, AllocValue, Heap, Trace, Tracer, UnpackValue, ValueLike}; use starlark::values::{starlark_value, NoSerialize, ProvidesStaticType}; use std::cell::RefCell; use std::fmt::Debug; use std::rc::Rc; use crate::engine::store::AxlStore; pub trait FutureAlloc: Send { fn alloc_value_fut<'v>(self: Box<Self>, heap: &'v Heap) -> values::Value<'v>; } impl StarlarkTypeRepr for Box<dyn FutureAlloc> { type Canonical = Self; fn starlark_type_repr() -> Ty { Ty::never() } } impl<'v> AllocValue<'v> for Box<dyn FutureAlloc> { fn alloc_value(self, heap: &'v Heap) -> values::Value<'v> { self.alloc_value_fut(heap) } } pub type FutOutput = Result<Box<dyn FutureAlloc>, anyhow::Error>; #[derive(Display, Allocative, ProvidesStaticType, NoSerialize)] #[display("Future")] pub struct StarlarkFuture { #[allocative(skip)] inner: Rc<RefCell<Option<BoxFuture<'static, FutOutput>>>>, } impl StarlarkFuture { pub fn from_future<T: FutureAlloc + Send + 'static>( fut: impl Future<Output = Result<T, anyhow::Error>> + Send + 'static, ) -> Self { use futures::TryFutureExt; Self { inner: Rc::new(RefCell::new(Some( fut.map_ok_or_else(|e| Err(e), |r| Ok(Box::new(r) as Box<dyn FutureAlloc>)) .boxed(), ))), } } pub fn as_fut(&self) -> impl Future<Output = FutOutput> + Send + 'static { let inner = self.inner.replace(None); let r = inner .ok_or(anyhow::anyhow!("future has already been awaited")) .unwrap(); r.into_future() } } impl Future for StarlarkFuture { type Output = FutOutput; fn poll( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Self::Output> { self.inner.take().unwrap().poll_unpin(cx) } } unsafe impl<'v> Trace<'v> for StarlarkFuture { fn trace(&mut self, _tracer: &Tracer<'v>) {} } impl Debug for StarlarkFuture { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Future").finish() } } impl<'v> AllocValue<'v> for StarlarkFuture { fn alloc_value(self, heap: &'v Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } } impl<'v> UnpackValue<'v> for StarlarkFuture { type Error = anyhow::Error; fn unpack_value_impl(value: values::Value<'v>) -> Result<Option<Self>, Self::Error> { let fut = value.downcast_ref_err::<StarlarkFuture>()?; Ok(Some(Self { inner: fut.inner.clone(), })) } } #[starlark_value(type = "Future")] impl<'v> values::StarlarkValue<'v> for StarlarkFuture { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(future_methods) } } #[starlark_module] pub(crate) fn future_methods(registry: &mut MethodsBuilder) { fn block<'v>( #[allow(unused)] this: values::Value<'v>, eval: &mut Evaluator<'v, '_, '_>, ) -> starlark::Result<values::Value<'v>> { let store = AxlStore::from_eval(eval)?; let this = this.downcast_ref_err::<StarlarkFuture>()?; let fut = this .inner .replace(None) .ok_or(anyhow::anyhow!("future has already been awaited"))?; let value = store.rt.block_on(fut)?; Ok(value.alloc_value_fut(eval.heap())) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/async/future_stream.rs
crates/axl-runtime/src/engine/async/future_stream.rs
use allocative::Allocative; use derive_more::Display; use starlark::values; use starlark::values::starlark_value; use starlark::values::AllocValue; use starlark::values::Heap; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::Trace; use std::sync::Arc; use tokio::sync::RwLock; use tokio::task::JoinSet; use super::future::StarlarkFuture; use super::rt::AsyncRuntime; #[derive(ProvidesStaticType, Display, NoSerialize, Allocative)] #[display("<FutureIterator>")] pub struct FutureIterator { #[allocative(skip)] pub(super) rt: AsyncRuntime, #[allocative(skip)] pub(super) stream: Arc<RwLock<JoinSet<super::future::FutOutput>>>, } impl std::fmt::Debug for FutureIterator { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("FutureIterator") .field("rt", &self.rt) .field("stream", &self.stream) .finish() } } impl FutureIterator { pub fn new(rt: AsyncRuntime, futures: Vec<StarlarkFuture>) -> Self { let mut set = JoinSet::new(); let guard = rt.enter(); for future in futures { set.spawn(future.as_fut()); } drop(guard); Self { rt, stream: Arc::new(RwLock::new(set)), } } } unsafe impl<'v> Trace<'v> for FutureIterator { fn trace(&mut self, _tracer: &values::Tracer<'v>) {} } impl Clone for FutureIterator { fn clone(&self) -> Self { todo!() } } impl<'v> AllocValue<'v> for FutureIterator { fn alloc_value(self, heap: &'v Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } } #[starlark_value(type = "FutureIterator")] impl<'v> values::StarlarkValue<'v> for FutureIterator { unsafe fn iterate( &self, me: values::Value<'v>, _heap: &'v Heap, ) -> starlark::Result<values::Value<'v>> { Ok(me) } unsafe fn iter_next(&self, _index: usize, heap: &'v Heap) -> Option<values::Value<'v>> { let stream: Arc<RwLock<JoinSet<_>>> = Arc::clone(&self.stream); let out = self.rt.block_on(async { tokio::task::spawn(async move { let mut stream = stream.write().await; stream.join_next().await }) .await .unwrap() }); let value = out?.ok()?; // TODO: Should stream stop when any of the futures result in error? Some(value.ok()?.alloc_value_fut(heap)) } unsafe fn iter_stop(&self) { // TODO: destroy the joinset, ensure nothing is left behind. } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/async/util.rs
crates/axl-runtime/src/engine/async/util.rs
use starlark::{ environment::GlobalsBuilder, eval::Evaluator, starlark_module, values::tuple::UnpackTuple, }; use crate::engine::store::AxlStore; use super::{future::StarlarkFuture, future_stream::FutureIterator}; pub fn register_globals(globals: &mut GlobalsBuilder) { globals.namespace("futures", register_future_utils); } #[starlark_module] fn register_future_utils(globals: &mut GlobalsBuilder) { fn iter<'v>( #[starlark(args)] futures: UnpackTuple<StarlarkFuture>, eval: &mut Evaluator<'v, '_, '_>, ) -> starlark::Result<FutureIterator> { let store = AxlStore::from_eval(eval)?; return Ok(FutureIterator::new(store.rt, futures.items)); } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/async/mod.rs
crates/axl-runtime/src/engine/async/mod.rs
use starlark::{ environment::GlobalsBuilder, starlark_module, values::starlark_value_as_type::StarlarkValueAsType, }; pub mod future; mod future_stream; pub mod util; pub mod rt { use starlark::values::ProvidesStaticType; use std::ops::Deref; use tokio::runtime::Handle; #[derive(Debug, ProvidesStaticType, Clone)] pub struct AsyncRuntime(pub Handle); impl AsyncRuntime { pub fn new() -> Self { Self(Handle::current()) } } impl Deref for AsyncRuntime { type Target = Handle; fn deref(&self) -> &Self::Target { &self.0 } } } #[starlark_module] fn register_types(globals: &mut GlobalsBuilder) { const Future: StarlarkValueAsType<future::StarlarkFuture> = StarlarkValueAsType::new(); } pub fn register_globals(globals: &mut GlobalsBuilder) { register_types(globals); util::register_globals(globals); }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/types/bytes.rs
crates/axl-runtime/src/engine/types/bytes.rs
use allocative::Allocative; use arc_slice::ArcBytes; use derive_more::Display; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::starlark_module; use starlark::values::AllocValue; use starlark::values::Value; use starlark::values; use starlark::values::starlark_value; use starlark::values::Heap; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::StarlarkValue; use starlark::values::Trace; #[derive(Debug, ProvidesStaticType, Display, Trace, NoSerialize, Allocative)] #[display("<Bytes>")] pub struct Bytes { #[allocative(skip)] pub(crate) buf: ArcBytes, } impl From<&[u8]> for Bytes { fn from(value: &[u8]) -> Self { Self { buf: ArcBytes::from_slice(value), } } } impl<'v> AllocValue<'v> for Bytes { fn alloc_value(self, heap: &'v Heap) -> Value<'v> { heap.alloc_complex_no_freeze(self) } } #[starlark_value(type = "Bytes")] impl<'v> StarlarkValue<'v> for Bytes { // Spec: The built-in len function returns the number of elements (bytes) in a bytes. fn length(&self) -> starlark::Result<i32> { Ok(self.buf.len() as i32) } // Spec: Two bytes values may be concatenated with the + operator. // fn add(&self, rhs: Value<'v>, heap: &'v Heap) -> Option<starlark::Result<Value<'v>>> { // let rhs = Bytes::from_value(rhs)?; // let slice = [self.buf.as_slice(), rhs.buf.as_slice()].concat(); // Some(Ok(heap.alloc_simple(Bytes { // buf: ArcSlice::from_slice(slice.as_slice()), // }))) // } // Spec: The slice expression b[i:j] returns the subsequence of b from index i up to but not including index j. // The index expression b[i] returns the int value of the ith element. fn slice( &self, _start: Option<Value<'v>>, _stop: Option<Value<'v>>, _stride: Option<Value<'v>>, _heap: &'v Heap, ) -> starlark::Result<Value<'v>> { values::ValueError::unsupported(self, "[::]") } // Spec: bool(bytes) would be equivalent to len(bytes) > 0 fn to_bool(&self) -> bool { self.buf.len() > 0 } // See: https://github.com/facebook/starlark-rust/issues/4#issuecomment-3420078819 fn collect_repr(&self, collector: &mut String) { collector.push_str(&String::from_utf8_lossy(&self.buf)); } fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(bytes_methods) } } #[starlark_module] fn bytes_methods(registry: &mut MethodsBuilder) {}
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/types/mod.rs
crates/axl-runtime/src/engine/types/mod.rs
pub mod bytes;
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/std/stream.rs
crates/axl-runtime/src/engine/std/stream.rs
use anyhow::anyhow; use starlark::values::list::AllocList; use starlark::values::Heap; use std::cell::RefCell; use std::fmt::Debug; use std::fmt::Display; use std::io::IsTerminal; use std::io::Read; use std::io::Stderr; use std::io::Stdin; use std::io::Stdout; use std::io::Write; use std::process::{ChildStderr, ChildStdin, ChildStdout}; use std::sync::Arc; use std::sync::Mutex; use allocative::Allocative; use dupe::Dupe; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::starlark_module; use starlark::starlark_simple_value; use starlark::values; use starlark::values::none::NoneType; use starlark::values::starlark_value; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::ValueLike; use crate::engine::std::stream_iter; #[derive(Debug, ProvidesStaticType, Dupe, Clone, NoSerialize, Allocative)] pub enum Readable { Stdin(#[allocative(skip)] Arc<Stdin>), ChildStderr(#[allocative(skip)] Arc<Mutex<RefCell<ChildStderr>>>), ChildStdout(#[allocative(skip)] Arc<Mutex<RefCell<ChildStdout>>>), } #[derive(Debug, ProvidesStaticType, Dupe, Clone, NoSerialize, Allocative)] pub enum Writable { ChildStdin(#[allocative(skip)] Arc<Mutex<RefCell<Option<ChildStdin>>>>), Stdout(#[allocative(skip)] Arc<Mutex<RefCell<Option<Stdout>>>>), Stderr(#[allocative(skip)] Arc<Mutex<RefCell<Option<Stderr>>>>), } impl Display for Readable { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Stdin(_) => write!(f, "stream<stdin>"), Self::ChildStderr(_) => write!(f, "stream<child_stderr>"), Self::ChildStdout(_) => write!(f, "stream<child_stdout>"), } } } impl Display for Writable { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::ChildStdin(_) => write!(f, "stream<child_stdin>"), Self::Stderr(_) => write!(f, "stream<stderr>"), Self::Stdout(_) => write!(f, "stream<stdout>"), } } } impl From<Stdin> for Readable { fn from(stdin: Stdin) -> Self { Self::Stdin(Arc::new(stdin)) } } impl From<ChildStderr> for Readable { fn from(stderr: ChildStderr) -> Self { Self::ChildStderr(Arc::new(Mutex::new(RefCell::new(stderr)))) } } impl From<ChildStdout> for Readable { fn from(stdout: ChildStdout) -> Self { Self::ChildStdout(Arc::new(Mutex::new(RefCell::new(stdout)))) } } impl From<ChildStdin> for Writable { fn from(stdin: ChildStdin) -> Self { Self::ChildStdin(Arc::new(Mutex::new(RefCell::new(Some(stdin))))) } } impl From<Stdout> for Writable { fn from(stdout: Stdout) -> Self { Self::Stdout(Arc::new(Mutex::new(RefCell::new(Some(stdout))))) } } impl From<Stderr> for Writable { fn from(stderr: Stderr) -> Self { Self::Stderr(Arc::new(Mutex::new(RefCell::new(Some(stderr))))) } } #[starlark_value(type = "std.io.Readable")] impl<'v> values::StarlarkValue<'v> for Readable { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(readable_methods) } unsafe fn iterate( &self, _me: values::Value<'v>, heap: &'v Heap, ) -> starlark::Result<values::Value<'v>> { Ok(heap.alloc_simple(stream_iter::ReadIterator::new(self.dupe()))) } } starlark_simple_value!(Readable); #[starlark_module] fn readable_methods(registry: &mut MethodsBuilder) { /// Returns true if the underlying stream is connected to a terminal/tty. #[starlark(attribute)] fn is_tty<'v>(this: values::Value) -> anyhow::Result<bool> { let io = this.downcast_ref_err::<Readable>()?; Ok(match &*io { Readable::Stdin(stdin) => stdin.is_terminal(), Readable::ChildStderr(_) => false, Readable::ChildStdout(_) => false, }) } /// Reads all bytes until EOF in this source, placing them into a list of bytes. /// /// If successful, this function will return the list of bytes read. fn read<'v>(this: values::Value) -> anyhow::Result<AllocList<Vec<u32>>> { let io = this.downcast_ref_err::<Readable>()?; let mut buf = vec![]; let _size = match &*io { Readable::Stdin(stdin) => stdin.lock().read(&mut buf)?, Readable::ChildStderr(stderr) => stderr.lock().unwrap().borrow_mut().read(&mut buf)?, Readable::ChildStdout(stdout) => stdout.lock().unwrap().borrow_mut().read(&mut buf)?, }; Ok(AllocList( buf.iter().map(|b| *b as u32).collect::<Vec<u32>>(), )) } /// Reads all bytes until EOF in this source and returns a string. /// /// If successful, this function will return all bytes as a string. fn read_to_string<'v>(this: values::Value) -> anyhow::Result<String> { let io = this.downcast_ref_err::<Readable>()?; let mut buf = String::new(); let _size = match &*io { Readable::Stdin(stdin) => stdin.lock().read_to_string(&mut buf)?, Readable::ChildStderr(stderr) => stderr .lock() .unwrap() .borrow_mut() .read_to_string(&mut buf)?, Readable::ChildStdout(stdout) => stdout .lock() .unwrap() .borrow_mut() .read_to_string(&mut buf)?, }; Ok(buf) } } #[starlark_value(type = "std.io.Writable")] impl<'v> values::StarlarkValue<'v> for Writable { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(writable_methods) } } starlark_simple_value!(Writable); #[starlark_module] fn writable_methods(registry: &mut MethodsBuilder) { /// Returns true if the underlying stream is connected to a terminal/tty. #[starlark(attribute)] fn is_tty<'v>(this: values::Value) -> anyhow::Result<bool> { let io = this.downcast_ref_err::<Writable>()?; Ok(match &*io { Writable::ChildStdin(_) => false, Writable::Stdout(out) => { let guard = out.lock().unwrap(); let borrowed = guard.borrow(); borrowed.as_ref().map(|s| s.is_terminal()).unwrap_or(false) } Writable::Stderr(err) => { let guard = err.lock().unwrap(); let borrowed = guard.borrow(); borrowed.as_ref().map(|s| s.is_terminal()).unwrap_or(false) } }) } /// Writes a buffer into this writer, returning how many bytes were written. /// /// This function will attempt to write the entire contents of `buf`, but /// the entire write may not succeed, or the write may also generate an /// error. Typically data is written from the start of the buffer and then /// caller should call `flush` to finish the write operation. fn write<'v>( this: values::Value, #[starlark(require = pos)] buf: values::StringValue, ) -> anyhow::Result<u32> { let io = this.downcast_ref_err::<Writable>()?; match &*io { Writable::ChildStdin(stdin) => { let guard = stdin.lock().unwrap(); let mut borrowed = guard.borrow_mut(); let inner = borrowed .as_mut() .ok_or_else(|| anyhow!("stream is closed"))?; inner .write(buf.as_bytes()) .map(|f| f as u32) .map_err(|err| anyhow!(err)) } Writable::Stdout(stdout) => { let guard = stdout.lock().unwrap(); let mut borrowed = guard.borrow_mut(); let inner = borrowed .as_mut() .ok_or_else(|| anyhow!("stream is closed"))?; inner .lock() .write(buf.as_bytes()) .map(|f| f as u32) .map_err(|err| anyhow!(err)) } Writable::Stderr(stderr) => { let guard = stderr.lock().unwrap(); let mut borrowed = guard.borrow_mut(); let inner = borrowed .as_mut() .ok_or_else(|| anyhow!("stream is closed"))?; inner .lock() .write(buf.as_bytes()) .map(|f| f as u32) .map_err(|err| anyhow!(err)) } } } /// Flushes this output stream, ensuring that all intermediately buffered /// contents reach their destination. fn flush<'v>(this: values::Value) -> anyhow::Result<NoneType> { let io = this.downcast_ref_err::<Writable>()?; match &*io { Writable::ChildStdin(stdin) => { let guard = stdin.lock().unwrap(); let mut borrowed = guard.borrow_mut(); if let Some(inner) = borrowed.as_mut() { inner.flush()?; } } Writable::Stdout(stdout) => { let guard = stdout.lock().unwrap(); let mut borrowed = guard.borrow_mut(); if let Some(inner) = borrowed.as_mut() { inner.lock().flush()?; } } Writable::Stderr(stderr) => { let guard = stderr.lock().unwrap(); let mut borrowed = guard.borrow_mut(); if let Some(inner) = borrowed.as_mut() { inner.lock().flush()?; } } }; Ok(NoneType) } /// Closes this output stream. This drops the underlying handle, and /// subsequent writes will fail with "stream is closed". fn close<'v>(this: values::Value) -> anyhow::Result<NoneType> { let io = this.downcast_ref_err::<Writable>()?; match &*io { Writable::ChildStdin(stdin) => { // Take the inner value out, replacing with None. Dropping it closes the stream. stdin .lock() .unwrap() .borrow_mut() .take() .ok_or_else(|| anyhow!("stream is already closed"))?; } Writable::Stdout(stdout) => { stdout .lock() .unwrap() .borrow_mut() .take() .ok_or_else(|| anyhow!("stream is already closed"))?; } Writable::Stderr(stderr) => { stderr .lock() .unwrap() .borrow_mut() .take() .ok_or_else(|| anyhow!("stream is already closed"))?; } }; Ok(NoneType) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/std/stream_iter.rs
crates/axl-runtime/src/engine/std/stream_iter.rs
use allocative::Allocative; use derive_more::Display; use starlark::starlark_simple_value; use starlark::values::AllocValue; use std::fmt::Debug; use std::io::Read; use starlark::typing::Ty; use starlark::values; use starlark::values::starlark_value; use starlark::values::Heap; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::Trace; use super::stream; #[derive(Debug, ProvidesStaticType, Display, Trace, NoSerialize, Allocative)] #[display("<ReadIterator>")] pub struct ReadIterator { #[allocative(skip)] readable: stream::Readable, } impl ReadIterator { pub fn new(readable: stream::Readable) -> Self { Self { readable } } } #[starlark_value(type = "ReadIterator")] impl<'v> values::StarlarkValue<'v> for ReadIterator { fn get_type_starlark_repr() -> Ty { Ty::iter(Ty::string()) } unsafe fn iter_next(&self, _index: usize, heap: &'v Heap) -> Option<values::Value<'v>> { let mut buf = vec![0; 65536]; let r = match &self.readable { stream::Readable::Stdin(stdin) => stdin.lock().read(&mut buf), stream::Readable::ChildStderr(err) => err.lock().unwrap().borrow_mut().read(&mut buf), stream::Readable::ChildStdout(out) => out.lock().unwrap().borrow_mut().read(&mut buf), }; if r.is_err() { return None; } let size = r.unwrap(); if size == 0 { return None; } Some(super::super::types::bytes::Bytes::from(&buf[0..size]).alloc_value(heap)) } unsafe fn iter_stop(&self) {} } starlark_simple_value!(ReadIterator);
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/std/process.rs
crates/axl-runtime/src/engine/std/process.rs
use std::cell::RefCell; use std::process; use std::process::Stdio; use std::rc::Rc; use allocative::Allocative; use anyhow::anyhow; use derive_more::Display; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::starlark_module; use starlark::starlark_simple_value; use starlark::values; use starlark::values::AllocValue; use starlark::values::Heap; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::Trace; use starlark::values::ValueLike; use starlark::values::list::UnpackList; use starlark::values::none::NoneOr; use starlark::values::none::NoneType; use starlark::values::starlark_value; use super::stream; #[derive(Debug, Display, ProvidesStaticType, NoSerialize, Allocative)] #[display("<std.process.Process>")] pub struct Process {} impl Process { pub fn new() -> Self { Self {} } } #[starlark_value(type = "std.process.Process")] impl<'v> values::StarlarkValue<'v> for Process { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(process_methods) } } starlark_simple_value!(Process); #[starlark_module] pub(crate) fn process_methods(registry: &mut MethodsBuilder) { fn command<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] program: values::StringValue, ) -> anyhow::Result<Command> { Ok(Command { inner: RefCell::new(process::Command::new(program.as_str())), }) } } #[derive(Debug, Display, Trace, ProvidesStaticType, NoSerialize, Allocative)] #[display("<std.process.Command>")] pub struct Command { #[allocative(skip)] inner: RefCell<process::Command>, } impl<'v> AllocValue<'v> for Command { fn alloc_value(self, heap: &'v Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } } #[starlark_value(type = "std.process.Command")] impl<'v> values::StarlarkValue<'v> for Command { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(command_methods) } } #[starlark_module] pub(crate) fn command_methods(registry: &mut MethodsBuilder) { fn arg<'v>( this: values::Value<'v>, #[starlark(require = pos)] arg: values::StringValue, ) -> anyhow::Result<values::Value<'v>> { let cmd = this.downcast_ref_err::<Command>()?; cmd.inner.borrow_mut().arg(arg.as_str()); Ok(this) } fn args<'v>( this: values::Value<'v>, #[starlark(require = pos)] args: UnpackList<values::StringValue>, ) -> anyhow::Result<values::Value<'v>> { let cmd = this.downcast_ref_err::<Command>()?; cmd.inner .borrow_mut() .args(args.items.iter().map(|f| f.as_str())); Ok(this) } fn env<'v>( this: values::Value<'v>, #[starlark(require = pos)] key: values::StringValue, #[starlark(require = pos)] value: NoneOr<values::StringValue>, ) -> anyhow::Result<values::Value<'v>> { let cmd = this.downcast_ref_err::<Command>()?; match value { NoneOr::None => cmd.inner.borrow_mut().env_remove(key.as_str()), NoneOr::Other(v) => cmd.inner.borrow_mut().env(key.as_str(), v.as_str()), }; Ok(this) } fn current_dir<'v>( this: values::Value<'v>, #[starlark(require = pos)] dir: values::StringValue, ) -> anyhow::Result<values::Value<'v>> { let cmd = this.downcast_ref_err::<Command>()?; cmd.inner.borrow_mut().current_dir(dir.as_str()); Ok(this) } /// Configuration for the child process's standard input (stdin) handle. /// /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and /// defaults to [`piped`] when used with [`output`]. fn stdin<'v>( this: values::Value<'v>, #[starlark(require = pos)] io: values::StringValue, ) -> anyhow::Result<values::Value<'v>> { let cmd = this.downcast_ref_err::<Command>()?; match io.as_str() { "null" => cmd.inner.borrow_mut().stdin(Stdio::null()), "piped" => cmd.inner.borrow_mut().stdin(Stdio::piped()), "inherit" => cmd.inner.borrow_mut().stdin(Stdio::inherit()), v => return Err(anyhow::anyhow!("invalid stdin type {v}")), }; Ok(this) } /// Configuration for the child process's standard output (stdout) handle. /// /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and /// defaults to [`piped`] when used with [`output`]. fn stdout<'v>( this: values::Value<'v>, #[starlark(require = pos)] io: values::StringValue, ) -> anyhow::Result<values::Value<'v>> { let cmd = this.downcast_ref_err::<Command>()?; match io.as_str() { "null" => cmd.inner.borrow_mut().stdout(Stdio::null()), "piped" => cmd.inner.borrow_mut().stdout(Stdio::piped()), "inherit" => cmd.inner.borrow_mut().stdout(Stdio::inherit()), v => return Err(anyhow::anyhow!("invalid stdout type {v}")), }; Ok(this) } /// Configuration for the child process's standard error (stderr) handle. /// /// Defaults to [`inherit`] when used with [`spawn`] or [`status`], and /// defaults to [`piped`] when used with [`output`]. fn stderr<'v>( this: values::Value<'v>, #[starlark(require = pos)] io: values::StringValue, ) -> anyhow::Result<values::Value<'v>> { let cmd = this.downcast_ref_err::<Command>()?; match io.as_str() { "null" => cmd.inner.borrow_mut().stderr(Stdio::null()), "piped" => cmd.inner.borrow_mut().stderr(Stdio::piped()), "inherit" => cmd.inner.borrow_mut().stderr(Stdio::inherit()), v => return Err(anyhow::anyhow!("invalid stderr type {v}")), }; Ok(this) } fn spawn<'v>(#[allow(unused)] this: values::Value<'v>) -> anyhow::Result<Child> { let cmd = this.downcast_ref_err::<Command>()?; let child = cmd.inner.borrow_mut().spawn()?; Ok(Child { inner: Rc::new(RefCell::new(Some(child))), }) } } #[derive(Debug, Display, Trace, ProvidesStaticType, NoSerialize, Allocative)] #[display("<std.process.Child>")] pub struct Child { #[allocative(skip)] inner: Rc<RefCell<Option<process::Child>>>, } impl<'v> AllocValue<'v> for Child { fn alloc_value(self, heap: &'v Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } } #[starlark_value(type = "std.process.Child")] impl<'v> values::StarlarkValue<'v> for Child { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(child_methods) } } #[starlark_module] pub(crate) fn child_methods(registry: &mut MethodsBuilder) { /// The handle for reading from the child’s standard output (stdout), if it has been captured. /// Calling this function more than once will yield error. fn stdout<'v>(this: values::Value<'v>) -> anyhow::Result<stream::Readable> { let child = this.downcast_ref_err::<Child>()?; let mut inner = child.inner.borrow_mut(); let inner = inner .as_mut() .ok_or(anyhow::anyhow!("child is no longer active"))?; let child_stdout = inner.stdout.take().ok_or(anyhow!( r#"stdout is not available. spawn the process with stdout("piped")."# ))?; Ok(stream::Readable::from(child_stdout)) } /// The handle for reading from the child’s standard error (stderr), if it has been captured. /// Calling this function more than once will yield error. fn stderr<'v>(this: values::Value<'v>) -> anyhow::Result<stream::Readable> { let child = this.downcast_ref_err::<Child>()?; let mut inner = child.inner.borrow_mut(); let inner = inner .as_mut() .ok_or(anyhow::anyhow!("child is no longer active"))?; let child_stderr = inner.stderr.take().ok_or(anyhow!( r#"stderr is not available. spawn the process with stderr("piped")."# ))?; Ok(stream::Readable::from(child_stderr)) } /// The handle for writing to the child’s standard input (stdin), if it has been captured. /// Calling this function more than once will yield error. fn stdin<'v>(this: values::Value<'v>) -> anyhow::Result<stream::Writable> { let child = this.downcast_ref_err::<Child>()?; let mut inner = child.inner.borrow_mut(); let inner = inner .as_mut() .ok_or(anyhow::anyhow!("child is no longer active"))?; let child_stdin = inner.stdin.take().ok_or(anyhow!( r#"stdin is not available. spawn the process with stdin("piped")."# ))?; Ok(stream::Writable::from(child_stdin)) } /// Returns the OS-assigned process identifier associated with this child. #[starlark(attribute)] fn id<'v>(this: values::Value<'v>) -> anyhow::Result<u32> { let child = this.downcast_ref_err::<Child>()?; Ok(child .inner .borrow() .as_ref() .ok_or(anyhow::anyhow!("child is no longer active"))? .id()) } /// Forces the child process to exit. If the child has already exited, its a no-op. /// /// This is equivalent to sending a SIGKILL on Unix platforms. fn kill<'v>(this: values::Value<'v>) -> anyhow::Result<NoneType> { let child = this.downcast_ref_err::<Child>()?; child .inner .borrow_mut() .as_mut() .ok_or(anyhow::anyhow!("child is no longer active"))? .kill()?; Ok(NoneType) } /// Waits for the child to exit completely, returning the status that it /// exited with. This function will continue to have the same return value /// after it has been called at least once. /// /// The stdin handle to the child process, if any, will be closed /// before waiting. This helps avoid deadlock: it ensures that the /// child does not block waiting for input from the parent, while /// the parent waits for the child to exit. fn wait<'v>(this: values::Value<'v>) -> anyhow::Result<ExitStatus> { let child = this.downcast_ref_err::<Child>()?; let status = child .inner .borrow_mut() .as_mut() .ok_or(anyhow::anyhow!("child is no longer active"))? .wait()?; Ok(ExitStatus(status)) } /// WARNING: Calling `wait_with_output` consumes the child instance, /// causing errors on subsequent calls to other methods. /// /// Simultaneously waits for the child to exit and collect all remaining /// output on the stdout/stderr handles, returning an `Output` /// instance. /// /// The stdin handle to the child process, if any, will be closed /// before waiting. This helps avoid deadlock: it ensures that the /// child does not block waiting for input from the parent, while /// the parent waits for the child to exit. /// /// By default, stdin, stdout and stderr are inherited from the parent. /// In order to capture the output into this `Result<Output>` it is /// necessary to create new pipes between parent and child. Use /// `stdout('piped')` or `stderr('piped')`, respectively. fn wait_with_output<'v>(this: values::Value<'v>) -> anyhow::Result<Output> { let child = this.downcast_ref_err::<Child>()?; let output = child .inner .replace(None) .ok_or(anyhow::anyhow!("child is no longer active"))? .wait_with_output()?; Ok(Output(output)) } } #[derive(Debug, Display, ProvidesStaticType, NoSerialize, Allocative)] #[display("<std.process.ExitStatus>")] pub struct ExitStatus(#[allocative(skip)] pub process::ExitStatus); #[starlark_value(type = "std.process.ExitStatus")] impl<'v> values::StarlarkValue<'v> for ExitStatus { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(exit_status_methods) } } starlark_simple_value!(ExitStatus); #[starlark_module] pub(crate) fn exit_status_methods(registry: &mut MethodsBuilder) { /// Was termination successful? Signal termination is not considered a /// success, and success is defined as a zero exit status. #[starlark(attribute)] fn success<'v>(this: values::Value<'v>) -> anyhow::Result<bool> { let out = this.downcast_ref_err::<ExitStatus>()?; Ok(out.0.success()) } /// Returns the exit code of the process, if any. /// /// In Unix terms the return value is the **exit status**: the value passed to `exit`, if the /// process finished by calling `exit`. Note that on Unix the exit status is truncated to 8 /// bits, and that values that didn't come from a program's call to `exit` may be invented by the /// runtime system (often, for example, 255, 254, 127 or 126). /// /// On Unix, this will return `None` if the process was terminated by a signal. #[starlark(attribute)] fn code<'v>(this: values::Value<'v>) -> anyhow::Result<NoneOr<i32>> { let out = this.downcast_ref_err::<ExitStatus>()?; Ok(NoneOr::from_option(out.0.code())) } /// If the process was terminated by a signal, returns that signal. /// /// In other words, if `WIFSIGNALED`, this returns `WTERMSIG`. /// /// Avability: UNIX #[starlark(attribute)] fn signal<'v>(this: values::Value<'v>) -> anyhow::Result<NoneOr<i32>> { #[cfg(unix)] { use std::os::unix::process::ExitStatusExt; let out = this.downcast_ref_err::<ExitStatus>()?; Ok(NoneOr::from_option(out.0.signal())) } #[cfg(not(unix))] { Ok(NoneOr::None) } } /// If the process was stopped by a signal, returns that signal. /// /// In other words, if `WIFSTOPPED`, this returns `WSTOPSIG`. This is only possible if the status came from /// a `wait` system call which was passed `WUNTRACED`, and was then converted into an `ExitStatus`. /// /// Avability: UNIX #[starlark(attribute)] fn stopped_signal<'v>(this: values::Value<'v>) -> anyhow::Result<NoneOr<i32>> { #[cfg(unix)] { use std::os::unix::process::ExitStatusExt; let out = this.downcast_ref_err::<ExitStatus>()?; Ok(NoneOr::from_option(out.0.stopped_signal())) } #[cfg(not(unix))] { Ok(NoneOr::None) } } } #[derive(Debug, Display, ProvidesStaticType, NoSerialize, Allocative)] #[display("<std.process.Output>")] pub struct Output(#[allocative(skip)] pub process::Output); #[starlark_value(type = "std.process.Output")] impl<'v> values::StarlarkValue<'v> for Output { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(output_methods) } } starlark_simple_value!(Output); #[starlark_module] pub(crate) fn output_methods(registry: &mut MethodsBuilder) { /// The status (exit code) of the process. #[starlark(attribute)] fn status<'v>(this: values::Value<'v>) -> anyhow::Result<ExitStatus> { let out = this.downcast_ref_err::<Output>()?; Ok(ExitStatus(out.0.status)) } /// The data that the process wrote to stderr. #[starlark(attribute)] fn stderr<'v>(this: values::Value<'v>) -> anyhow::Result<String> { let out = this.downcast_ref_err::<Output>()?; Ok(String::from_utf8(out.0.stderr.clone())?) } /// The data that the process wrote to stdout. #[starlark(attribute)] fn stdout<'v>(this: values::Value<'v>) -> anyhow::Result<String> { let out = this.downcast_ref_err::<Output>()?; Ok(String::from_utf8(out.0.stdout.clone())?) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/std/io.rs
crates/axl-runtime/src/engine/std/io.rs
use std::fmt::Debug; use allocative::Allocative; use derive_more::Display; use dupe::Dupe; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::starlark_module; use starlark::starlark_simple_value; use starlark::values; use starlark::values::starlark_value; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::ValueLike; use super::stream; #[derive(Debug, Display, ProvidesStaticType, NoSerialize, Allocative)] #[display("<std.io.Stdio>")] pub struct Stdio { stdout: stream::Writable, stderr: stream::Writable, stdin: stream::Readable, } impl Stdio { pub fn new() -> Self { Self { stdout: stream::Writable::from(std::io::stdout()), stderr: stream::Writable::from(std::io::stderr()), stdin: stream::Readable::from(std::io::stdin()), } } } #[starlark_value(type = "std.io.Stdio")] impl<'v> values::StarlarkValue<'v> for Stdio { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(stdio_methods) } } starlark_simple_value!(Stdio); #[starlark_module] pub(crate) fn stdio_methods(registry: &mut MethodsBuilder) { /// Returns a writable stream for the standard output of the current process. #[starlark(attribute)] fn stdout<'v>(this: values::Value) -> anyhow::Result<stream::Writable> { let this = this.downcast_ref_err::<Stdio>()?; Ok(this.stdout.dupe()) } /// Returns a writable stream for the standard error of the current process. #[starlark(attribute)] fn stderr<'v>(this: values::Value) -> anyhow::Result<stream::Writable> { let this = this.downcast_ref_err::<Stdio>()?; Ok(this.stderr.dupe()) } /// Returns a readable stream for the standard input of the current process. #[starlark(attribute)] fn stdin<'v>(this: values::Value) -> anyhow::Result<stream::Readable> { let this = this.downcast_ref_err::<Stdio>()?; Ok(this.stdin.dupe()) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/std/fs.rs
crates/axl-runtime/src/engine/std/fs.rs
use allocative::Allocative; use derive_more::Display; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::values::list::UnpackList; use starlark::values::none::NoneType; use starlark::values::ValueOfUnchecked; use std::fs; use std::time::UNIX_EPOCH; use starlark::starlark_module; use starlark::starlark_simple_value; use starlark::values; use starlark::values::starlark_value; use starlark::values::Heap; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::StringValue; use starlark::values::Trace; #[derive(Debug, Clone, ProvidesStaticType, Display, Trace, NoSerialize, Allocative)] #[display("<fs.DirEntry path:{path} is_dir:{is_dir} is_file:{is_file}>")] pub struct DirEntry<'v> { path: StringValue<'v>, is_file: values::Value<'v>, is_dir: values::Value<'v>, } #[starlark_value(type = "fs.DirEntry")] impl<'v> values::StarlarkValue<'v> for DirEntry<'v> { fn get_attr(&self, attr: &str, _: &Heap) -> Option<values::Value<'v>> { match attr { "path" => Some(self.path.to_value()), "is_file" => Some(self.is_file), "is_dir" => Some(self.is_dir), _ => None, } } fn dir_attr(&self) -> Vec<String> { vec!["path".into(), "is_file".into(), "is_dir".into()] } } impl<'v> values::AllocValue<'v> for DirEntry<'v> { fn alloc_value(self, heap: &'v values::Heap) -> values::Value<'v> { heap.alloc_complex(self) } } #[derive(Debug, Display, ProvidesStaticType, NoSerialize, Allocative)] #[display("<fs.DirEntry>")] pub struct FrozenDirEntry { path: values::FrozenValue, is_file: values::FrozenValue, is_dir: values::FrozenValue, } #[starlark_value(type = "fs.DirEntry")] impl<'v> values::StarlarkValue<'v> for FrozenDirEntry { type Canonical = DirEntry<'v>; } impl<'v> values::Freeze for DirEntry<'v> { type Frozen = FrozenDirEntry; fn freeze(self, freezer: &values::Freezer) -> values::FreezeResult<Self::Frozen> { Ok(FrozenDirEntry { path: freezer.freeze(self.path.to_value())?, is_dir: freezer.freeze(self.is_dir)?, is_file: freezer.freeze(self.is_file)?, }) } } starlark_simple_value!(FrozenDirEntry); #[derive(Debug, Clone, ProvidesStaticType, Display, Trace, NoSerialize, Allocative)] #[display("<fs.Metadata is_dir:{is_dir} is_file:{is_file} is_symlink:{is_symlink} size:{size}>")] pub struct Metadata<'v> { is_dir: values::Value<'v>, is_file: values::Value<'v>, is_symlink: values::Value<'v>, size: values::Value<'v>, modified: values::Value<'v>, accessed: values::Value<'v>, created: values::Value<'v>, readonly: values::Value<'v>, } #[starlark_value(type = "fs.Metadata")] impl<'v> values::StarlarkValue<'v> for Metadata<'v> { fn get_attr(&self, attr: &str, _: &Heap) -> Option<values::Value<'v>> { match attr { "is_dir" => Some(self.is_dir), "is_file" => Some(self.is_file), "is_symlink" => Some(self.is_symlink), "size" => Some(self.size), "modified" => Some(self.modified), "accessed" => Some(self.accessed), "created" => Some(self.created), "readonly" => Some(self.readonly), _ => None, } } fn dir_attr(&self) -> Vec<String> { vec![ "is_dir".into(), "is_file".into(), "is_symlink".into(), "size".into(), "modified".into(), "accessed".into(), "created".into(), "readonly".into(), ] } } impl<'v> values::AllocValue<'v> for Metadata<'v> { fn alloc_value(self, heap: &'v values::Heap) -> values::Value<'v> { heap.alloc_complex(self) } } #[derive(Debug, Display, ProvidesStaticType, NoSerialize, Allocative)] #[display("<fs.Metadata>")] pub struct FrozenMetadata { is_dir: values::FrozenValue, is_file: values::FrozenValue, is_symlink: values::FrozenValue, size: values::FrozenValue, modified: values::FrozenValue, accessed: values::FrozenValue, created: values::FrozenValue, readonly: values::FrozenValue, } #[starlark_value(type = "fs.Metadata")] impl<'v> values::StarlarkValue<'v> for FrozenMetadata { type Canonical = Metadata<'v>; } impl<'v> values::Freeze for Metadata<'v> { type Frozen = FrozenMetadata; fn freeze(self, freezer: &values::Freezer) -> values::FreezeResult<Self::Frozen> { Ok(FrozenMetadata { is_dir: freezer.freeze(self.is_dir)?, is_file: freezer.freeze(self.is_file)?, is_symlink: freezer.freeze(self.is_symlink)?, size: freezer.freeze(self.size)?, modified: freezer.freeze(self.modified)?, accessed: freezer.freeze(self.accessed)?, created: freezer.freeze(self.created)?, readonly: freezer.freeze(self.readonly)?, }) } } starlark_simple_value!(FrozenMetadata); #[derive(Debug, Display, ProvidesStaticType, NoSerialize, Allocative)] #[display("<std.Filesystem>")] pub struct Filesystem {} impl Filesystem { pub fn new() -> Self { Self {} } } #[starlark_value(type = "std.Filesystem")] impl<'v> values::StarlarkValue<'v> for Filesystem { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(filesystem_methods) } } starlark_simple_value!(Filesystem); #[starlark_module] pub(crate) fn filesystem_methods(registry: &mut MethodsBuilder) { /// Copies the contents of one file to another. This function will also copy the permission bits of the original file to the destination file. /// /// This function will overwrite the contents of to. /// Note that if from and to both point to the same file, then the file will likely get truncated by this operation. /// On success, the total number of bytes copied is returned and it is equal to the length of the to file as reported by metadata. /// /// This function will return an error in the following situations, but is not limited to just these cases: /// - from is neither a regular file nor a symlink to a regular file. /// - from does not exist. /// - The current process does not have the permission rights to read from or write to. /// - The parent directory of to doesn’t exist. fn copy<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] from: values::StringValue, #[starlark(require = pos)] to: values::StringValue, ) -> anyhow::Result<u64> { Ok(fs::copy(from.as_str(), to.as_str())?) } /// Creates a new, empty directory at the provided path. /// /// This function will return an error in the following situations, but is not limited to just these cases: /// - User lacks permissions to create directory at path. /// - A parent of the given path doesn’t exist. (To create a directory and all its missing parents at the same time, use the create_dir_all function.) /// - path already exists. /// /// NOTE: If a parent of the given path doesn’t exist, this function will return an error. To create a directory and all its missing parents at the same time, use the create_dir_all function. fn create_dir<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, ) -> anyhow::Result<NoneType> { fs::create_dir(path.as_str())?; Ok(NoneType) } /// Recursively create a directory and all of its parent components if they are missing. /// /// This function is not atomic. If it returns an error, any parent components it was able to create will remain. /// If the empty path is passed to this function, it always succeeds without creating any directories. /// /// The function will return an error if any directory specified in path does not exist and could not be created. There may be other error conditions; see create_dir for specifics. fn create_dir_all<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, ) -> anyhow::Result<NoneType> { fs::create_dir_all(path.as_str())?; Ok(NoneType) } /// Creates a new hard link on the filesystem. /// /// The link path will be a link pointing to the original path. Note that systems often require these two paths to both be located on the same filesystem. /// /// If original names a symbolic link, it is platform-specific whether the symbolic link is followed. On platforms where it’s possible to not follow it, it is not followed, and the created hard link points to the symbolic link itself. /// /// This function will return an error in the following situations, but is not limited to just these cases: /// - The original path is not a file or doesn’t exist. /// - The ‘link’ path already exists. fn hard_link<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] original: values::StringValue, #[starlark(require = pos)] link: values::StringValue, ) -> anyhow::Result<NoneType> { fs::hard_link(original.as_str(), link.as_str())?; Ok(NoneType) } /// Returns `true` if the path points at an existing entity. /// /// This function will traverse symbolic links to query information about the /// destination file. In case of broken symbolic links this will return `false`. /// /// Note that while this avoids some pitfalls of the `exists()` method, it still can not /// prevent time-of-check to time-of-use (TOCTOU) bugs. You should only use it in scenarios /// where those bugs are not an issue. fn exists<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, ) -> anyhow::Result<bool> { Ok(fs::exists(path.as_str())?) } /// Returns true if this path is for a directory. /// /// This function will return an error in the following situations, but is not limited to just these cases: /// - The user lacks permissions to perform metadata call on path. /// - path does not exist. fn is_dir<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, ) -> anyhow::Result<bool> { let metadata = fs::metadata(path.as_str())?; Ok(metadata.is_dir()) } /// Returns true if this path is for a regular file. /// /// This function will return an error in the following situations, but is not limited to just these cases: /// - The user lacks permissions to perform metadata call on path. /// - path does not exist. fn is_file<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, ) -> anyhow::Result<bool> { println!( r#"Deprecated: is_file is deprecated and will be removed in a future version of AXL. Use `fs.metadata().is_file` instead."# ); let metadata = fs::metadata(path.as_str())?; Ok(metadata.is_file()) } /// Returns the metadata about the given file or directory. /// /// This function will return an error in the following situations, but is not limited to just these cases: /// - The user lacks permissions to perform metadata call on path. /// - path does not exist. /// /// The modified, accessed, created fields of the Metadata result might not be available on all platforms, and will /// be set to None on platforms where they is not available. fn metadata<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, heap: &'v Heap, ) -> anyhow::Result<Metadata<'v>> { let m = fs::metadata(path.as_str())?; Ok(marshal_metadata(&m, heap)) } /// Returns an iterator over the entries within a directory. /// /// This function will return an error in the following situations, but is not limited to just these cases: /// - The provided path doesn’t exist. /// - The process lacks permissions to view the contents. /// - The path points at a non-directory file. fn read_dir<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, heap: &'v Heap, ) -> anyhow::Result<ValueOfUnchecked<'v, UnpackList<DirEntry<'v>>>> { let metadata = fs::read_dir(path.as_str())?; Ok(heap .alloc_typed_unchecked(values::list::AllocList(metadata.map(|entry| { let entry = entry.unwrap(); let file_type = entry.file_type().unwrap(); DirEntry { path: heap.alloc_str(entry.file_name().to_str().unwrap()), // TODO: implement a filetype and expose that. is_dir: heap.alloc(file_type.is_dir()), is_file: heap.alloc(file_type.is_file()), } // TODO: return a iterator of DirEntry type. }))) .cast()) } /// Reads a symbolic link, returning the file that the link points to. /// /// This function will return an error in the following situations, but is not limited to just these cases: /// - path is not a symbolic link. /// - path does not exist. fn read_link<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, heap: &'v Heap, ) -> anyhow::Result<values::StringValue<'v>> { let r = fs::read_link(path.as_str()) .map(|f| heap.alloc_str(&f.as_os_str().to_string_lossy().to_string()))?; Ok(r) } /// Reads the entire contents of a file into a string. /// /// This function will return an error under a number of different circumstances. Some of these error conditions are: /// - The specified file does not exist. /// - The user lacks permission to get the specified access rights for the file. /// - The user lacks permission to open one of the directory components of the specified path. fn read_to_string<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, heap: &'v Heap, ) -> anyhow::Result<values::StringValue<'v>> { let r = fs::read_to_string(path.as_str()).map(|f| heap.alloc_str(f.as_str()))?; Ok(r) } /// Removes an empty directory. /// /// If you want to remove a directory that is not empty, as well as all /// of its contents recursively, consider using remove_dir_all instead. /// /// This function will return an error in the following situations, but is not limited to just these cases: /// - path doesn’t exist. /// - path isn’t a directory. /// - The user lacks permissions to remove the directory at the provided path. /// - The directory isn’t empty. fn remove_dir<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, ) -> anyhow::Result<NoneType> { fs::remove_dir(path.as_str())?; Ok(NoneType) } /// Removes a directory at this path, after removing all its contents. Use carefully! /// /// This function does not follow symbolic links and it will simply remove the symbolic link itself. /// /// See remove_file and remove_dir for possible errors. fn remove_dir_all<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, ) -> anyhow::Result<NoneType> { fs::remove_dir_all(path.as_str())?; Ok(NoneType) } /// Removes a file from the filesystem. /// /// Note that there is no guarantee that the file is immediately deleted /// (e.g., depending on platform, other open file descriptors may prevent immediate removal). /// /// This function will return an error in the following situations, but is not limited to just these cases: /// - path points to a directory. /// - The file doesn’t exist. /// - The user lacks permissions to remove the file. fn remove_file<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, ) -> anyhow::Result<NoneType> { fs::remove_file(path.as_str())?; Ok(NoneType) } /// Renames a file or directory to a new name, replacing the original file if to already exists. /// /// This will not work if the new name is on a different mount point. /// /// This function will return an error in the following situations, but is not limited to just these cases: /// - from does not exist. /// - The user lacks permissions to view contents. /// - from and to are on separate filesystems. fn rename<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] from: values::StringValue, #[starlark(require = pos)] to: values::StringValue, ) -> anyhow::Result<NoneType> { fs::rename(from.as_str(), to.as_str())?; Ok(NoneType) } // TODO: add set_permissions // NB: Don't add deprecated soft_link (https://doc.rust-lang.org/std/fs/fn.soft_link.html); // instead add std.os.unix.fs.symlink to follow Rust's convention of not adding // os specific function to non-os specific std lib location. /// Queries the metadata about a file without following symlinks. /// /// This function will return an error in the following situations, but is not limited to just these cases: /// - The user lacks permissions to perform metadata call on path. /// - path does not exist. /// /// The modified, accessed, created fields of the Metadata result might not be available on all platforms, and will /// be set to None on platforms where they is not available. fn symlink_metadata<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, heap: &'v Heap, ) -> anyhow::Result<Metadata<'v>> { let m = fs::symlink_metadata(path.as_str())?; Ok(marshal_metadata(&m, heap)) } /// Writes a string as the entire contents of a file. /// /// This function will create a file if it does not exist, and will entirely replace its contents if it does. /// Depending on the platform, this function may fail if the full directory path does not exist. /// This is a convenience function for using fs.create and [write_all] with fewer imports. fn write<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] path: values::StringValue, #[starlark(require = pos)] content: values::StringValue, ) -> anyhow::Result<NoneType> { fs::write(path.as_str(), content.as_str())?; Ok(NoneType) } } fn marshal_metadata<'v>(m: &fs::Metadata, heap: &'v Heap) -> Metadata<'v> { let file_type = m.file_type(); let modified = match m.modified() { Ok(t) => match t.duration_since(UNIX_EPOCH) { Ok(d) => heap.alloc(d.as_micros() as u64), Err(_) => heap.alloc(NoneType), }, Err(_) => heap.alloc(NoneType), }; let accessed = match m.accessed() { Ok(t) => match t.duration_since(UNIX_EPOCH) { Ok(d) => heap.alloc(d.as_micros() as u64), Err(_) => heap.alloc(NoneType), }, Err(_) => heap.alloc(NoneType), }; let created = match m.created() { Ok(t) => match t.duration_since(UNIX_EPOCH) { Ok(d) => heap.alloc(d.as_micros() as u64), Err(_) => heap.alloc(NoneType), }, Err(_) => heap.alloc(NoneType), }; let permissions = m.permissions(); Metadata { is_dir: heap.alloc(file_type.is_dir()), is_file: heap.alloc(file_type.is_file()), is_symlink: heap.alloc(file_type.is_symlink()), size: heap.alloc(m.len()), modified, accessed, created, readonly: heap.alloc(permissions.readonly()), } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/std/env.rs
crates/axl-runtime/src/engine/std/env.rs
use allocative::Allocative; use derive_more::Display; use starlark::environment::{Methods, MethodsBuilder, MethodsStatic}; use starlark::eval::Evaluator; use starlark::values::list::{AllocList, UnpackList}; use starlark::values::none::NoneOr; use starlark::values::tuple::{AllocTuple, UnpackTuple}; use starlark::values::{starlark_value, StarlarkValue}; use starlark::values::{Heap, NoSerialize, ProvidesStaticType, ValueOfUnchecked}; use starlark::{starlark_module, starlark_simple_value, values}; use crate::engine::store::AxlStore; #[derive(Clone, Debug, ProvidesStaticType, NoSerialize, Allocative, Display)] #[display("<std.Env>")] pub struct Env {} impl Env { pub fn new() -> Self { Self {} } } /// Documentation here #[starlark_value(type = "std.Env")] impl<'v> StarlarkValue<'v> for Env { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(env_methods) } } starlark_simple_value!(Env); #[starlark_module] pub(crate) fn env_methods(registry: &mut MethodsBuilder) { /// Returns the version of the Aspect CLI. fn aspect_cli_version<'v>( #[allow(unused)] this: values::Value<'v>, eval: &mut Evaluator<'v, '_, '_>, ) -> anyhow::Result<values::StringValue<'v>> { let store = AxlStore::from_eval(eval)?; Ok(eval.heap().alloc_str(&store.cli_version)) } /// Fetches the environment variable key from the current process. fn var<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(require = pos)] key: values::StringValue<'v>, heap: &'v Heap, ) -> anyhow::Result<NoneOr<values::StringValue<'v>>> { let val = std::env::var(key.as_str()) .map(|val| heap.alloc_str(val.as_str())) .ok(); Ok(NoneOr::from_option(val)) } /// Returns an iterator of (variable, value) pairs of strings, for all the /// environment variables of the current process. /// /// The returned iterator contains a snapshot of the process's environment /// variables at the time of this invocation. Modifications to environment /// variables afterwards will not be reflected in the returned iterator. fn vars<'v>( #[allow(unused)] this: values::Value<'v>, heap: &'v Heap, ) -> anyhow::Result< ValueOfUnchecked< 'v, UnpackList<ValueOfUnchecked<'v, UnpackTuple<values::StringValue<'v>>>>, >, > { Ok(heap .alloc_typed_unchecked(AllocList(std::env::vars().map(|(k, v)| { let val = [heap.alloc_str(k.as_str()), heap.alloc_str(v.as_str())]; heap.alloc_typed_unchecked(AllocTuple(val)) .cast::<UnpackTuple<values::StringValue<'v>>>() }))) .cast()) } /// Returns the path of a temporary directory. /// /// The temporary directory may be shared among users, or between processes /// with different privileges; thus, the creation of any files or directories /// in the temporary directory must use a secure method to create a uniquely /// named file. Creating a file or directory with a fixed or predictable name /// may result in "insecure temporary file" security vulnerabilities. Consider /// using a crate that securely creates temporary files or directories. /// /// Note that the returned value may be a symbolic link, not a directory. /// /// /// **Platform**-specific behavior /// /// On Unix, returns the value of the `TMPDIR` environment variable if it is /// set, otherwise the value is OS-specific: /// - On Darwin-based OSes (macOS, iOS, etc) it returns the directory provided /// by `confstr(_CS_DARWIN_USER_TEMP_DIR, ...)`, as recommended by [Apple's /// security guidelines][appledoc]. /// - On all other unix-based OSes, it returns `/tmp`. /// /// On Windows, the behavior is equivalent to that of [`GetTempPath2`][GetTempPath2] / /// [`GetTempPath`][GetTempPath], which this function uses internally. /// /// [GetTempPath2]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppath2a /// [GetTempPath]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppatha /// [appledoc]: https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html#//apple_ref/doc/uid/TP40002585-SW10 fn temp_dir<'v>( #[allow(unused)] this: values::Value<'v>, heap: &'v Heap, ) -> anyhow::Result<values::StringValue<'v>> { Ok(heap.alloc_str( std::env::temp_dir() // to_str() returns None() if string is not UTF-8 (https://doc.rust-lang.org/std/path/struct.Path.html#method.to_str) .to_str() .ok_or(anyhow::anyhow!("temp directory is non utf-8"))?, )) } /// Returns the path of the current user's home directory if known. /// /// This may return `None` if getting the directory fails or if the platform does not have user home directories. /// /// For storing user data and configuration it is often preferable to use more specific directories. /// For example, [XDG Base Directories] on Unix or the `LOCALAPPDATA` and `APPDATA` environment variables on Windows. /// /// [XDG Base Directories]: https://specifications.freedesktop.org/basedir-spec/latest/ /// /// **Unix** /// /// - Returns the value of the 'HOME' environment variable if it is set /// (including to an empty string). /// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function /// using the UID of the current user. An empty home directory field returned from the /// `getpwuid_r` function is considered to be a valid value. /// - Returns `None` if the current user has no entry in the /etc/passwd file. /// /// **Windows** /// /// - Returns the value of the 'USERPROFILE' environment variable if it is set, and is not an empty string. /// - Otherwise, [`GetUserProfileDirectory`][msdn] is used to return the path. This may change in the future. /// /// [msdn]: https://docs.microsoft.com/en-us/windows/win32/api/userenv/nf-userenv-getuserprofiledirectorya /// /// In UWP (Universal Windows Platform) targets this function is unimplemented and always returns `None`. fn home_dir<'v>( #[allow(unused)] this: values::Value<'v>, heap: &'v Heap, ) -> anyhow::Result<NoneOr<values::StringValue<'v>>> { Ok(match std::env::home_dir() { Some(path) => NoneOr::Other( heap.alloc_str( path // to_str() returns None() if string is not UTF-8 (https://doc.rust-lang.org/std/path/struct.Path.html#method.to_str) .to_str() .ok_or(anyhow::anyhow!("home directory is non utf-8"))?, ), ), None => NoneOr::None, }) } /// Returns the current working directory as a path. /// /// **Platform**-specific behavior /// /// This function currently corresponds to the `getcwd` function on Unix /// and the `GetCurrentDirectoryW` function on Windows. /// /// /// **Errors** /// /// Fails if the current working directory value is invalid. /// Possible cases: /// /// * Current directory does not exist. /// * There are insufficient permissions to access the current directory. /// fn current_dir<'v>( #[allow(unused)] this: values::Value<'v>, heap: &'v Heap, ) -> anyhow::Result<values::StringValue<'v>> { Ok(heap.alloc_str( std::env::current_dir()? .to_str() // to_str() returns None() if string is not UTF-8 (https://doc.rust-lang.org/std/path/struct.Path.html#method.to_str) .ok_or(anyhow::anyhow!("current directory is non utf-8"))?, )) } fn current_exe<'v>( #[allow(unused)] this: values::Value<'v>, heap: &'v Heap, ) -> anyhow::Result<values::StringValue<'v>> { Ok(heap.alloc_str( std::env::current_exe()? .to_str() // to_str() returns None() if string is not UTF-8 (https://doc.rust-lang.org/std/path/struct.Path.html#method.to_str) .ok_or(anyhow::anyhow!("current executable is non utf-8"))?, )) } /// Returns the project root directory. /// /// This project root directory is found starting at current working directory and searching upwards /// through its ancestors for repository boundary marker files (such as `MODULE.aspect`, `MODULE.bazel`, /// `MODULE.bazel.lock`, `REPO.bazel`, `WORKSPACE`, or `WORKSPACE.bazel`). The first ancestor directory /// containing any of these files is considered the project root. If no such directory is found, the /// current directory is used as the project root. fn root_dir<'v>( #[allow(unused)] this: values::Value<'v>, eval: &mut Evaluator<'v, '_, '_>, ) -> anyhow::Result<values::StringValue<'v>> { let store = AxlStore::from_eval(eval)?; Ok(eval.heap().alloc_str( &store .root_dir .to_str() // to_str() returns None() if string is not UTF-8 (https://doc.rust-lang.org/std/path/struct.Path.html#method.to_str) .ok_or(anyhow::anyhow!("root dir is non utf-8"))?, )) } /// Returns the operating system name. /// /// Returns a string describing the operating system in use, such as /// "linux", "macos", "windows", etc. fn os<'v>( #[allow(unused)] this: values::Value<'v>, _heap: &'v Heap, ) -> anyhow::Result<&'v str> { Ok(std::env::consts::OS) } /// Returns the CPU architecture. /// /// Returns a string describing the CPU architecture, such as /// "x86_64", "aarch64", etc. fn arch<'v>( #[allow(unused)] this: values::Value<'v>, _heap: &'v Heap, ) -> anyhow::Result<&'v str> { Ok(std::env::consts::ARCH) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/std/mod.rs
crates/axl-runtime/src/engine/std/mod.rs
use allocative::Allocative; use derive_more::Display; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::starlark_simple_value; use starlark::values; use starlark::values::starlark_value; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::{ environment::GlobalsBuilder, starlark_module, values::starlark_value_as_type::StarlarkValueAsType, }; mod env; mod fs; mod io; mod process; mod stream; mod stream_iter; #[derive(Debug, Display, ProvidesStaticType, NoSerialize, Allocative)] #[display("<std.Std>")] pub struct Std {} starlark_simple_value!(Std); #[starlark_value(type = "std.Std")] impl<'v> values::StarlarkValue<'v> for Std { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(std_methods) } } #[starlark_module] pub(crate) fn std_methods(registry: &mut MethodsBuilder) { #[starlark(attribute)] fn env<'v>(#[allow(unused)] this: values::Value<'v>) -> starlark::Result<env::Env> { Ok(env::Env::new()) } #[starlark(attribute)] fn io<'v>(this: values::Value<'v>) -> starlark::Result<io::Stdio> { Ok(io::Stdio::new()) } #[starlark(attribute)] fn fs<'v>(#[allow(unused)] this: values::Value<'v>) -> starlark::Result<fs::Filesystem> { Ok(fs::Filesystem::new()) } #[starlark(attribute)] fn process<'v>(#[allow(unused)] this: values::Value<'v>) -> starlark::Result<process::Process> { Ok(process::Process::new()) } } #[starlark_module] fn register_types(globals: &mut GlobalsBuilder) { const Env: StarlarkValueAsType<env::Env> = StarlarkValueAsType::new(); const FileSystem: StarlarkValueAsType<fs::Filesystem> = StarlarkValueAsType::new(); const Std: StarlarkValueAsType<Std> = StarlarkValueAsType::new(); } #[starlark_module] fn register_process_types(globals: &mut GlobalsBuilder) { const Child: StarlarkValueAsType<process::Child> = StarlarkValueAsType::new(); const Command: StarlarkValueAsType<process::Command> = StarlarkValueAsType::new(); const ExitStatus: StarlarkValueAsType<process::ExitStatus> = StarlarkValueAsType::new(); const Output: StarlarkValueAsType<process::Output> = StarlarkValueAsType::new(); const Process: StarlarkValueAsType<process::Process> = StarlarkValueAsType::new(); } #[starlark_module] fn register_io_types(globals: &mut GlobalsBuilder) { const Stdio: StarlarkValueAsType<io::Stdio> = StarlarkValueAsType::new(); const Readable: StarlarkValueAsType<stream::Readable> = StarlarkValueAsType::new(); const Writable: StarlarkValueAsType<stream::Writable> = StarlarkValueAsType::new(); } pub fn register_globals(globals: &mut GlobalsBuilder) { register_types(globals); globals.namespace("process", register_process_types); globals.namespace("io", register_io_types); }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/helpers.rs
crates/axl-runtime/src/engine/bazel/helpers.rs
pub fn join_strings(items: &[impl AsRef<str>], sep: &str) -> String { if items.is_empty() { return String::new(); } items .iter() .map(|s| s.as_ref()) .collect::<Vec<_>>() .join(sep) } pub fn format_bazel_command( startup_flags: &Vec<String>, verb: &str, flags: &Vec<String>, targets: &Vec<String>, ) -> String { let startup_str = join_strings(&startup_flags, " "); let flags_str = join_strings(&flags, " "); let targets_str = join_strings(&targets, " "); let mut parts: Vec<String> = Vec::new(); parts.push("bazel".to_string()); if !startup_str.is_empty() { parts.push(startup_str); } parts.push(verb.to_string()); if !flags_str.is_empty() { parts.push(flags_str); } parts.push("--".to_string()); if !targets_str.is_empty() { parts.push(targets_str); } join_strings(&parts, " ") }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/build.rs
crates/axl-runtime/src/engine/bazel/build.rs
use std::cell::RefCell; use std::collections::HashMap; use std::env::var; use std::io; use std::process::Child; use std::process::Command; use std::process::Stdio; use std::rc::Rc; use std::thread::JoinHandle; use allocative::Allocative; use anyhow::anyhow; use derive_more::Display; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::starlark_module; use starlark::starlark_simple_value; use starlark::values; use starlark::values::none::NoneOr; use starlark::values::starlark_value; use starlark::values::AllocValue; use starlark::values::Heap; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::Trace; use starlark::values::UnpackValue; use starlark::values::ValueLike; use crate::engine::r#async::rt::AsyncRuntime; use super::helpers::format_bazel_command; use super::iter::BuildEventIterator; use super::iter::ExecutionLogIterator; use super::iter::WorkspaceEventIterator; use super::stream::BuildEventStream; use super::stream::ExecLogStream; use super::stream::WorkspaceEventStream; use super::stream_sink::GrpcEventStreamSink; use super::stream_tracing::TracingEventStreamSink; fn debug_mode() -> bool { match var("ASPECT_DEBUG") { Ok(val) => !val.is_empty(), _ => false, } } #[derive(Debug, ProvidesStaticType, Display, Trace, NoSerialize, Allocative)] #[display("<bazel.build.BuildStatus>")] pub struct BuildStatus { success: bool, code: Option<i32>, } impl<'v> AllocValue<'v> for BuildStatus { fn alloc_value(self, heap: &'v Heap) -> values::Value<'v> { heap.alloc_simple(self) } } #[starlark_value(type = "bazel.build.BuildStatus")] impl<'v> values::StarlarkValue<'v> for BuildStatus { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(build_status_methods) } } #[starlark_module] pub(crate) fn build_status_methods(registry: &mut MethodsBuilder) { #[starlark(attribute)] fn success<'v>(this: values::Value<'v>) -> anyhow::Result<bool> { Ok(this.downcast_ref::<BuildStatus>().unwrap().success) } #[starlark(attribute)] fn code<'v>(this: values::Value<'v>) -> anyhow::Result<NoneOr<i32>> { Ok(NoneOr::from_option( this.downcast_ref::<BuildStatus>().unwrap().code, )) } } #[derive(Debug, Display, ProvidesStaticType, NoSerialize, Allocative, Clone)] #[display("<bazel.build.BuildEventSink>")] pub enum BuildEventSink { Grpc { uri: String, metadata: HashMap<String, String>, }, } starlark_simple_value!(BuildEventSink); #[starlark_value(type = "bazel.build.BuildEventSink")] impl<'v> values::StarlarkValue<'v> for BuildEventSink {} impl<'v> UnpackValue<'v> for BuildEventSink { type Error = anyhow::Error; fn unpack_value_impl(value: values::Value<'v>) -> Result<Option<Self>, Self::Error> { let value = value.downcast_ref_err::<BuildEventSink>()?; Ok(Some(value.clone())) } } impl BuildEventSink { fn spawn(&self, rt: AsyncRuntime, stream: &BuildEventStream) -> JoinHandle<()> { match self { BuildEventSink::Grpc { uri, metadata } => { GrpcEventStreamSink::spawn(rt, stream.receiver(), uri.clone(), metadata.clone()) } } } } #[derive(Debug, Display, ProvidesStaticType, Trace, NoSerialize, Allocative)] #[display("<bazel.build.Build>")] pub struct Build { #[allocative(skip)] build_event_stream: RefCell<Option<BuildEventStream>>, #[allocative(skip)] workspace_event_stream: RefCell<Option<WorkspaceEventStream>>, #[allocative(skip)] execlog_stream: RefCell<Option<ExecLogStream>>, #[allocative(skip)] sink_handles: RefCell<Vec<JoinHandle<()>>>, #[allocative(skip)] child: Rc<RefCell<Child>>, #[allocative(skip)] span: RefCell<tracing::span::EnteredSpan>, } impl Build { pub fn pid() -> io::Result<u32> { let mut cmd = Command::new("bazel"); cmd.arg("info"); cmd.arg("server_pid"); cmd.stdout(Stdio::piped()); cmd.stderr(Stdio::null()); cmd.stdin(Stdio::null()); let c = cmd.spawn()?.wait_with_output()?; if !c.status.success() { return Err(io::Error::other(anyhow!("failed to determine Bazel pid"))); } let bytes: [u8; 4] = c.stdout[0..4].try_into().unwrap(); Ok(u32::from_be_bytes(bytes)) } // TODO: this should return a thiserror::Error pub fn spawn( verb: &str, targets: impl IntoIterator<Item = String>, (build_events, sinks): (bool, Vec<BuildEventSink>), execution_logs: bool, workspace_events: bool, flags: Vec<String>, startup_flags: Vec<String>, inherit_stdout: bool, inherit_stderr: bool, rt: AsyncRuntime, ) -> Result<Build, std::io::Error> { let pid = Self::pid()?; let span = tracing::info_span!( "ctx.bazel.build", build_events = build_events, workspace_events = workspace_events, execution_logs = execution_logs, flags = ?flags ) .entered(); let targets: Vec<String> = targets.into_iter().collect(); if debug_mode() { eprintln!( "running {}", format_bazel_command(&startup_flags, verb, &flags, &targets) ); } let mut cmd = Command::new("bazel"); cmd.args(startup_flags); cmd.arg(verb); let build_event_stream = if build_events { let (out, stream) = BuildEventStream::spawn_with_pipe(pid)?; cmd.arg("--build_event_publish_all_actions") .arg("--build_event_binary_file_upload_mode=fully_async") .arg("--build_event_binary_file") .arg(&out); Some(stream) } else { None }; let workspace_event_stream = if workspace_events { let (out, stream) = WorkspaceEventStream::spawn_with_pipe(pid)?; cmd.arg("--experimental_workspace_rules_log_file").arg(&out); Some(stream) } else { None }; let execlog_stream = if execution_logs { let (out, stream) = ExecLogStream::spawn_with_pipe(pid)?; cmd.arg("--execution_log_compact_file").arg(&out); Some(stream) } else { None }; // Build Event sinks for forwarding the build events let mut sink_handles: Vec<JoinHandle<()>> = vec![]; for sink in sinks { let handle = sink.spawn(rt.clone(), build_event_stream.as_ref().unwrap()); sink_handles.push(handle); } if build_events { sink_handles.push(TracingEventStreamSink::spawn( rt, build_event_stream.as_ref().unwrap().receiver(), )) } cmd.args(flags); cmd.arg("--"); // separate flags from target patterns (not strictly necessary for build & test verbs but good form) cmd.args(targets); // TODO: if not inheriting, we should pipe and make the streams available to AXL cmd.stdout(if inherit_stdout { Stdio::inherit() } else { Stdio::null() }); cmd.stderr(if inherit_stderr { Stdio::inherit() } else { Stdio::null() }); cmd.stdin(Stdio::null()); let child = cmd.spawn()?; Ok(Self { child: Rc::new(RefCell::new(child)), build_event_stream: RefCell::new(build_event_stream), workspace_event_stream: RefCell::new(workspace_event_stream), execlog_stream: RefCell::new(execlog_stream), sink_handles: RefCell::new(sink_handles), span: RefCell::new(span), }) } } impl<'v> AllocValue<'v> for Build { fn alloc_value(self, heap: &'v Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } } #[starlark_value(type = "bazel.build.Build")] impl<'v> values::StarlarkValue<'v> for Build { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(build_methods) } } #[starlark_module] pub(crate) fn build_methods(registry: &mut MethodsBuilder) { // Creates an iterable `BuildEventIterator` type. // Every call to this function will return a new iterator. // TODO: explain backpressure and build events sinks falling behind on poor network conditions. fn build_events<'v>(this: values::Value<'v>) -> anyhow::Result<BuildEventIterator> { let build = this.downcast_ref::<Build>().unwrap(); let event_stream = build.build_event_stream.borrow(); let event_stream = event_stream.as_ref().ok_or(anyhow::anyhow!( "call `ctx.bazel.build` with `build_events = true` in order to receive build events." ))?; Ok(BuildEventIterator::new(event_stream.receiver())) } // Creates an iterable `ExecutionLogIterator` type. // Every call to this function will return a new iterator. fn execution_logs<'v>(this: values::Value<'v>) -> anyhow::Result<ExecutionLogIterator> { let build = this.downcast_ref::<Build>().unwrap(); let execlog_stream = build.execlog_stream.borrow(); let execlog_stream = execlog_stream.as_ref().ok_or(anyhow::anyhow!( "call `ctx.bazel.build` with `execution_logs = true` in order to receive execution log events." ))?; Ok(ExecutionLogIterator::new(execlog_stream.receiver())) } // Creates an iterable `WorkspaceEventIterator` type. // Every call to this function will return a new iterator. fn workspace_events<'v>(this: values::Value<'v>) -> anyhow::Result<WorkspaceEventIterator> { let build = this.downcast_ref::<Build>().unwrap(); let event_stream = build.workspace_event_stream.borrow(); let event_stream = event_stream.as_ref().ok_or(anyhow::anyhow!( "call `ctx.bazel.build` with `workspace_events = true` in order to receive workspace events." ))?; Ok(WorkspaceEventIterator::new(event_stream.receiver())) } fn try_wait<'v>(this: values::Value<'v>) -> anyhow::Result<NoneOr<BuildStatus>> { let build = this.downcast_ref_err::<Build>()?; let status = build.child.borrow_mut().try_wait()?; Ok(match status { Some(status) => NoneOr::Other(BuildStatus { success: status.success(), code: status.code(), }), None => NoneOr::None, }) } fn wait<'v>(this: values::Value<'v>) -> anyhow::Result<BuildStatus> { let build = this.downcast_ref_err::<Build>()?; let result = build.child.borrow_mut().wait()?; // TODO: consider adding a wait_events() method for granular control. // Wait for BES stream to complete. let build_event_stream = build.build_event_stream.take(); if let Some(event_stream) = build_event_stream { match event_stream.join() { Ok(_) => {} // TODO: tell the user which one and why Err(err) => anyhow::bail!("build event stream thread error: {}", err), } }; // Wait for Workspace event stream to complete. let workspace_event_stream = build.workspace_event_stream.take(); if let Some(workspace_event_stream) = workspace_event_stream { match workspace_event_stream.join() { Ok(_) => {} // TODO: tell the user which one and why Err(err) => anyhow::bail!("workspace event stream thread error: {}", err), } }; // Wait for Execlog stream to complete. let execlog_stream = build.execlog_stream.take(); if let Some(execlog_stream) = execlog_stream { match execlog_stream.join() { Ok(_) => {} // TODO: tell the user which one and why Err(err) => anyhow::bail!("execlog stream thread error: {}", err), } }; let handles = build.sink_handles.take(); for handle in handles { match handle.join() { Ok(_) => continue, // TODO: tell the user which one and why Err(err) => anyhow::bail!("one of the sinks failed: {:#?}", err), } } // BES ends here let span = build.span.replace(tracing::trace_span!("build").entered()); span.exit(); Ok(BuildStatus { success: result.success(), code: result.code(), }) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/mod.rs
crates/axl-runtime/src/engine/bazel/mod.rs
use std::collections::HashMap; use allocative::Allocative; use derive_more::Display; use either::Either; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::eval::Evaluator; use starlark::starlark_simple_value; use starlark::values; use starlark::values::dict::UnpackDictEntries; use starlark::values::list::UnpackList; use starlark::values::starlark_value; use starlark::values::tuple::UnpackTuple; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::{ environment::GlobalsBuilder, starlark_module, values::starlark_value_as_type::StarlarkValueAsType, }; use crate::engine::store::AxlStore; use axl_proto; mod build; mod helpers; mod iter; mod query; mod stream; mod stream_sink; mod stream_tracing; #[derive(Debug, Display, ProvidesStaticType, NoSerialize, Allocative)] #[display("<bazel.Bazel>")] pub struct Bazel {} starlark_simple_value!(Bazel); #[starlark_value(type = "bazel.Bazel")] impl<'v> values::StarlarkValue<'v> for Bazel { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(bazel_methods) } } #[starlark_module] pub(crate) fn bazel_methods(registry: &mut MethodsBuilder) { /// Build targets Bazel within AXL with ctx.bazel.build(). /// The result is a `Build` object, which has `artifacts()` (TODO), /// `failures()` (TODO), and a `events()` functions that provide /// iterators to the artifacts, failures, events respectively. /// /// Running `ctx.bazel.build()` does not block the Starlark thread. Explicitly /// call `.wait()` on the `Build` object to wait until the invocation finishes. /// /// You can pass in a single target or target pattern to build. /// /// **Examples** /// /// ```python /// def _fancy_build_impl(ctx): /// io = ctx.std.io /// build = ctx.bazel.build( /// "//target/to:build" /// build_events = True, /// ) /// for event in build.build_events(): /// if event.type == "progress": /// io.stdout.write(event.payload.stdout) /// io.stderr.write(event.payload.stderr) /// ``` fn build<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(args)] targets: UnpackTuple<values::StringValue>, #[starlark(require = named, default = Either::Left(false))] build_events: Either< bool, UnpackList<build::BuildEventSink>, >, #[starlark(require = named, default = false)] workspace_events: bool, #[starlark(require = named, default = false)] execution_logs: bool, #[starlark(require = named, default = UnpackList::default())] flags: UnpackList< values::StringValue, >, #[starlark(require = named, default = UnpackList::default())] startup_flags: UnpackList< values::StringValue, >, #[starlark(require = named, default = false)] inherit_stdout: bool, #[starlark(require = named, default = true)] inherit_stderr: bool, eval: &mut Evaluator<'v, '_, '_>, ) -> anyhow::Result<build::Build> { let build_events = match build_events { Either::Left(events) => (events, vec![]), Either::Right(sinks) => (true, sinks.items), }; let store = AxlStore::from_eval(eval)?; let build = build::Build::spawn( "build", targets.items.iter().map(|f| f.as_str().to_string()), build_events, execution_logs, workspace_events, flags.items.iter().map(|f| f.as_str().to_string()).collect(), startup_flags .items .iter() .map(|f| f.as_str().to_string()) .collect(), inherit_stdout, inherit_stderr, store.rt, )?; Ok(build) } /// Build & test Bazel targets within AXL with ctx.bazel.test(). /// The result is a `Build` object, which has `artifacts()` (TODO), /// `failures()` (TODO), and a `events()` functions that provide /// iterators to the artifacts, failures, events respectively. /// /// Running `ctx.bazel.test()` does not block the Starlark thread. Explicitly /// call `.wait()` on the `Build` object to wait until the invocation finishes. /// /// You can pass in a single target or target pattern to test. /// /// **Examples** /// /// ```python /// def _fancy_test_impl(ctx): /// io = ctx.std.io /// test = ctx.bazel.test( /// "//target/to:test" /// build_events = True, /// ) /// for event in test.build_events(): /// if event.type == "progress": /// io.stdout.write(event.payload.stdout) /// io.stderr.write(event.payload.stderr) /// ``` fn test<'v>( #[allow(unused)] this: values::Value<'v>, #[starlark(args)] targets: UnpackTuple<values::StringValue>, #[starlark(require = named, default = Either::Left(false))] build_events: Either< bool, UnpackList<build::BuildEventSink>, >, #[starlark(require = named, default = false)] workspace_events: bool, #[starlark(require = named, default = false)] execution_logs: bool, #[starlark(require = named, default = UnpackList::default())] flags: UnpackList< values::StringValue, >, #[starlark(require = named, default = UnpackList::default())] startup_flags: UnpackList< values::StringValue, >, #[starlark(require = named, default = false)] inherit_stdout: bool, #[starlark(require = named, default = true)] inherit_stderr: bool, eval: &mut Evaluator<'v, '_, '_>, ) -> anyhow::Result<build::Build> { let build_events = match build_events { Either::Left(events) => (events, vec![]), Either::Right(sinks) => (true, sinks.items), }; let store = AxlStore::from_eval(eval)?; let test = build::Build::spawn( "test", targets.items.iter().map(|f| f.as_str().to_string()), build_events, execution_logs, workspace_events, flags.items.iter().map(|f| f.as_str().to_string()).collect(), startup_flags .items .iter() .map(|f| f.as_str().to_string()) .collect(), inherit_stdout, inherit_stderr, store.rt, )?; Ok(test) } /// The query system provides a programmatic interface for analyzing build dependencies /// and target relationships. Queries are constructed using a chain API and are lazily /// evaluated only when `.eval()` is explicitly called. /// /// The entry point is `ctx.bazel.query()`, which returns a `query` for creating initial /// query expressions. Most operations operate on `query` objects, which represent /// sets of targets that can be filtered, transformed, and combined. /// /// **Example** /// /// ```starlark /// **Query** dependencies of a target /// deps = ctx.bazel.query().targets("//myapp:main").deps() /// all_deps = deps.eval() /// /// **Chain** multiple operations /// sources = ctx.bazel.query().targets("//myapp:main") /// .deps() /// .kind("source file") /// .eval() /// ``` fn query<'v>(#[allow(unused)] this: values::Value<'v>) -> starlark::Result<query::Query> { Ok(query::Query::new()) } } #[starlark_module] fn register_build_events(globals: &mut GlobalsBuilder) { #[starlark(as_type = build::BuildEventSink)] fn grpc( #[starlark(require = named)] uri: String, #[starlark(require = named, default = UnpackDictEntries::default())] metadata: UnpackDictEntries<String, String>, ) -> starlark::Result<build::BuildEventSink> { // TODO: validate endpoint Ok(build::BuildEventSink::Grpc { uri: uri.replace("grpcs://", "https://"), metadata: HashMap::from_iter(metadata.entries), }) } } #[starlark_module] fn register_build_types(globals: &mut GlobalsBuilder) { const Build: StarlarkValueAsType<build::Build> = StarlarkValueAsType::new(); const BuildEventIterator: StarlarkValueAsType<iter::BuildEventIterator> = StarlarkValueAsType::new(); const BuildEventSink: StarlarkValueAsType<build::BuildEventSink> = StarlarkValueAsType::new(); const BuildStatus: StarlarkValueAsType<build::BuildStatus> = StarlarkValueAsType::new(); const ExecutionLogIterator: StarlarkValueAsType<iter::ExecutionLogIterator> = StarlarkValueAsType::new(); const WorkspaceEventIterator: StarlarkValueAsType<iter::WorkspaceEventIterator> = StarlarkValueAsType::new(); } #[starlark_module] fn register_query_types(globals: &mut GlobalsBuilder) { const Query: StarlarkValueAsType<query::Query> = StarlarkValueAsType::new(); const TargetSet: StarlarkValueAsType<query::TargetSet> = StarlarkValueAsType::new(); } #[starlark_module] fn register_types(globals: &mut GlobalsBuilder) { const Bazel: StarlarkValueAsType<Bazel> = StarlarkValueAsType::new(); } pub fn register_globals(globals: &mut GlobalsBuilder) { register_types(globals); globals.namespace("query", |globals| { register_query_types(globals); axl_proto::blaze_query_toplevels(globals); }); globals.namespace("build", |globals| { register_build_types(globals); globals.namespace("build_event", axl_proto::build_event_stream_toplevels); globals.namespace("execution_log", axl_proto::tools_protos_toplevels); globals.namespace("workspace_event", axl_proto::workspace_log_toplevels); }); globals.namespace("build_events", |globals| { register_build_events(globals); }); }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/query.rs
crates/axl-runtime/src/engine/bazel/query.rs
use std::cell::RefCell; use std::env::temp_dir; use std::fs; use std::fs::File; use std::io::Read; use std::process::Command; use std::process::Stdio; use std::rc::Rc; use allocative::Allocative; use anyhow::anyhow; use derive_more::Display; use dupe::Dupe; use prost::bytes::Bytes; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::starlark_module; use starlark::typing::Ty; use starlark::values; use starlark::values::starlark_value; use starlark::values::type_repr::StarlarkTypeRepr; use starlark::values::AllocValue; use starlark::values::Heap; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::Trace; use starlark::values::ValueLike; use axl_proto::blaze_query as query; use prost::Message; #[derive(Debug, Clone)] pub enum Target { // We leave environment_group out as its undocumented. // https://github.com/bazelbuild/bazel/issues/10849 SourceFile(query::SourceFile), GeneratedFile(query::GeneratedFile), Rule(query::Rule), PackageGroup(query::PackageGroup), } impl TryFrom<query::Target> for Target { type Error = anyhow::Error; fn try_from(value: query::Target) -> Result<Self, Self::Error> { match value.r#type() { query::target::Discriminator::Rule => Ok(Self::Rule( value .rule .ok_or(anyhow::anyhow!("rule field is not set."))?, )), query::target::Discriminator::SourceFile => Ok(Self::SourceFile( value .source_file .ok_or(anyhow::anyhow!("source_file field is not set."))?, )), query::target::Discriminator::GeneratedFile => { Ok(Self::GeneratedFile(value.generated_file.ok_or( anyhow::anyhow!("generated_file field is not set."), )?)) } query::target::Discriminator::PackageGroup => { Ok(Self::PackageGroup(value.package_group.ok_or( anyhow::anyhow!("package_group field is not set."), )?)) } query::target::Discriminator::EnvironmentGroup => Err(anyhow::anyhow!("not supported")), } } } impl<'v> StarlarkTypeRepr for Target { type Canonical = Self; fn starlark_type_repr() -> Ty { Ty::unions(vec![ Ty::starlark_value::<query::Rule>(), Ty::starlark_value::<query::SourceFile>(), Ty::starlark_value::<query::GeneratedFile>(), Ty::starlark_value::<query::PackageGroup>(), ]) } } impl<'v> starlark::values::AllocValue<'v> for Target { fn alloc_value(self, heap: &'v starlark::values::Heap) -> starlark::values::Value<'v> { match self { Target::SourceFile(source_file) => heap.alloc_simple(source_file), Target::GeneratedFile(generated_file) => heap.alloc_simple(generated_file), Target::Rule(rule) => heap.alloc_simple(rule), Target::PackageGroup(package_group) => heap.alloc_simple(package_group), } } } #[derive(Debug, ProvidesStaticType, Display, Trace, NoSerialize, Allocative)] #[display("<bazel.query.TargetSet {targets:?}>")] pub struct TargetSet { #[allocative(skip)] targets: Vec<Target>, } impl<'v> AllocValue<'v> for TargetSet { fn alloc_value(self, heap: &'v Heap) -> values::Value<'v> { heap.alloc_simple(self) } } #[starlark_value(type = "bazel.query.TargetSet")] impl<'v> values::StarlarkValue<'v> for TargetSet { fn get_type_starlark_repr() -> Ty { Ty::iter(Target::starlark_type_repr()) } fn length(&self) -> starlark::Result<i32> { Ok(self.targets.len() as i32) } fn at(&self, index: values::Value<'v>, heap: &'v Heap) -> starlark::Result<values::Value<'v>> { let idx = index.unpack_i32().ok_or(anyhow!("pass an int"))?; let target = self .targets .get(idx as usize) .map(|t| heap.alloc(t.clone())) .ok_or(anyhow!("no target at index {idx}"))?; Ok(target) } fn iterate_collect(&self, heap: &'v Heap) -> starlark::Result<Vec<values::Value<'v>>> { Ok(self .targets .clone() .into_iter() .map(|f| heap.alloc(f)) .collect()) } } #[derive(Dupe, Clone, Debug, Display, ProvidesStaticType, Trace, NoSerialize, Allocative)] #[display("<bazel.query.Query>")] pub struct Query { #[allocative(skip)] // Expr here has to be mutable expr: Rc<RefCell<String>>, } impl Query { pub fn new() -> Self { Self { expr: Rc::new(RefCell::new(String::new())), } } pub fn query(expr: &str) -> anyhow::Result<TargetSet> { let mut cmd = Command::new("bazel"); cmd.arg("query"); cmd.arg(expr); cmd.arg("--output=streamed_proto"); let out = temp_dir().join("query.bin"); let _ = fs::remove_file(&out); let outfile = File::create(&out)?; cmd.stderr(Stdio::null()); cmd.stdout(outfile); cmd.stdin(Stdio::null()); cmd.spawn()?.wait()?; let mut buf = vec![]; File::open(&out)?.read_to_end(&mut buf)?; let mut buf2 = Bytes::from(buf); let mut targets = vec![]; loop { let target = query::Target::decode_length_delimited(&mut buf2); match target { Ok(target) => { let target = target.try_into(); if target.is_ok() { targets.push(target.unwrap()); } } // TODO: only break if error is EOF Err(_) => break, } } Ok(TargetSet { targets }) } } impl<'v> AllocValue<'v> for Query { fn alloc_value(self, heap: &'v Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } } #[starlark_value(type = "bazel.query.Query")] /// The entry point for programmatic queries, providing methods to construct initial target sets. /// /// This builder allows creating starting points for queries, such as target patterns or explicit /// label sets. All operations return a `TargetSet` which can be further composed. impl<'v> values::StarlarkValue<'v> for Query { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(query_methods) } } #[starlark_module] pub(crate) fn query_methods(registry: &mut MethodsBuilder) { /// Replaces the query `expression` with a raw query expression string. /// /// This escape hatch allows direct use of the underlying query language for complex cases, /// while still supporting further chaining. /// /// ```starlark /// **Complex** intersection query /// complex = ctx.bazel.query().raw("deps(//foo) intersect kind('test', //bar:*)") /// /// **Path**-based query /// path_query = ctx.bazel.query().raw("somepath(//start, //end)") /// /// **Chaining** after raw /// filtered = complex.kind("source file") /// ``` fn raw<'v>( this: values::Value<'v>, #[starlark(require = pos)] expr: values::StringValue, ) -> anyhow::Result<Query> { use dupe::Dupe; let query = this.downcast_ref_err::<Query>()?; query.expr.replace(expr.as_str().to_string()); Ok(query.dupe()) } /// The query system provides a programmatic interface for analyzing build dependencies /// and target relationships. Queries are constructed using a chain API and are lazily /// evaluated only when `.eval()` is explicitly called. /// /// The entry point is `ctx.bazel.query()`, which returns a `query` for creating initial /// query expressions. Most operations operate on `query` objects, which represent /// sets of targets that can be filtered, transformed, and combined. /// /// **Example** /// /// ```starlark /// **Query** dependencies of a target /// deps = ctx.bazel.query().targets("//myapp:main").deps() /// all_deps: target_set = deps.eval() /// /// **Chain** multiple operations /// sources = ctx.bazel.query().targets("//myapp:main") /// .deps() /// .kind("source file") /// .eval() /// ``` fn eval<'v>(this: values::Value<'v>) -> anyhow::Result<TargetSet> { let this = this.downcast_ref_err::<Query>()?; let expr = this.expr.borrow(); Query::query(expr.as_str()) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/stream_sink.rs
crates/axl-runtime/src/engine/bazel/stream_sink.rs
use std::{ collections::HashMap, thread::{self, JoinHandle}, }; use axl_proto::{ build_event_stream::BuildEvent, google::devtools::build::v1::{BuildStatus, PublishBuildToolEventStreamRequest}, }; use build_event_stream::{ build_tool, client::{Client, ClientError}, lifecycle, }; use fibre::spmc::{Receiver, RecvError}; use thiserror::Error; use tokio::{sync::mpsc::error::SendError, task}; use tokio_stream::{wrappers::ReceiverStream, StreamExt}; use super::super::r#async::rt::AsyncRuntime; #[derive(Error, Debug)] pub enum SinkError { #[error(transparent)] RecvError(#[from] RecvError), #[error(transparent)] ClientError(#[from] ClientError), #[error(transparent)] SendError(#[from] SendError<PublishBuildToolEventStreamRequest>), } #[derive(Debug)] pub struct GrpcEventStreamSink {} impl GrpcEventStreamSink { pub fn spawn( rt: AsyncRuntime, recv: Receiver<BuildEvent>, endpoint: String, headers: HashMap<String, String>, ) -> JoinHandle<()> { thread::spawn(move || { rt.block_on(async { GrpcEventStreamSink::task_spawn(recv, endpoint, headers) .await .await }) .expect("failed to join") .expect("failed to wait") }) } pub async fn task_spawn( recv: Receiver<BuildEvent>, endpoint: String, headers: HashMap<String, String>, ) -> task::JoinHandle<Result<(), SinkError>> { tokio::task::spawn(GrpcEventStreamSink::work(recv, endpoint, headers)) } async fn work( recv: Receiver<BuildEvent>, endpoint: String, headers: HashMap<String, String>, ) -> Result<(), SinkError> { let mut client = Client::new(endpoint, headers).await?; let recv = recv.clone(); let uuid = uuid::Uuid::new_v4().to_string(); let build_id = uuid.to_string(); let invocation_id = uuid.to_string(); client .publish_lifecycle_event(lifecycle::build_enqueued( build_id.to_string(), invocation_id.to_string(), )) .await?; client .publish_lifecycle_event(lifecycle::invocation_started( build_id.to_string(), invocation_id.to_string(), )) .await?; let mut seq = 0; let (sender, receiver) = tokio::sync::mpsc::channel::<PublishBuildToolEventStreamRequest>(1); let rstream = ReceiverStream::new(receiver); let stream = client.publish_build_tool_event_stream(rstream); let (a, b): (Result<(), SinkError>, Result<(), SinkError>) = tokio::join!( async { let mut stream = stream.await?.into_inner(); while let Some(event) = stream.next().await { match event { // Succesfully received BES event ack // TODO: Use this information to control how many inflight BES events we should be // sending. Ok(_ev) => {} Err(err) => eprintln!("{}", err), } } Ok(()) }, async { loop { seq += 1; let event = recv.recv(); if event.is_err() { break; } let event = event.unwrap(); sender .send(build_tool::bazel_event( build_id.to_string(), invocation_id.to_string(), seq, &event, )) .await?; if event.last_message { drop(sender); break; } } Ok(()) } ); a?; b?; client .publish_lifecycle_event(lifecycle::invocation_finished( build_id.to_string(), invocation_id.to_string(), BuildStatus { result: 0, final_invocation_id: build_id.to_string(), build_tool_exit_code: Some(0), error_message: String::new(), details: None, }, )) .await?; client .publish_lifecycle_event(lifecycle::build_finished( build_id.to_string(), invocation_id.to_string(), )) .await?; Ok(()) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/stream_tracing.rs
crates/axl-runtime/src/engine/bazel/stream_tracing.rs
use std::{ collections::HashMap, thread::{self, JoinHandle}, time::SystemTime, }; use axl_proto::{ build_event_stream::{build_event::Payload, build_event_id::Id, BuildEvent}, Timestamp, }; use fibre::spmc::Receiver; use tokio::task; use tracing::{span::EnteredSpan, Level, Span}; use super::super::r#async::rt::AsyncRuntime; #[derive(Debug)] pub struct TracingEventStreamSink {} fn timestamp_or_now(timestamp: Option<&Timestamp>) -> i64 { timestamp.map_or_else( || { SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap() .as_secs() as i64 }, |t| t.seconds, ) } impl TracingEventStreamSink { pub fn spawn(rt: AsyncRuntime, recv: Receiver<BuildEvent>) -> JoinHandle<()> { let span = tracing::info_span!("events"); thread::spawn(move || { rt.block_on(async { TracingEventStreamSink::task_spawn(span, recv).await.await }) .expect("failed to join") }) } pub async fn task_spawn(span: Span, recv: Receiver<BuildEvent>) -> task::JoinHandle<()> { tokio::task::spawn(async move { let _guard = span.enter(); let mut spans: HashMap<&str, EnteredSpan> = HashMap::new(); loop { let event = recv.recv(); if event.is_err() { break; } let event = event.unwrap(); let id = event.id.as_ref().unwrap().id.as_ref().unwrap(); match (event.payload.unwrap(), id) { (_, Id::Fetch(id)) => { tracing::event!(name: "fetch", Level::INFO, url = ?id.url); } (Payload::OptionsParsed(opt), Id::OptionsParsed(_)) => { tracing::event!( name: "options_parsed", Level::INFO, build_tool = opt.tool_tag, command_line = ?opt.cmd_line ); } (Payload::Action(action), Id::ActionCompleted(id)) => { if action.start_time.is_some() && action.end_time.is_some() { let start_time = timestamp_or_now(action.start_time.as_ref()); let end_time = timestamp_or_now(action.end_time.as_ref()); let span = tracing::info_span!( "action", otel.start_time = start_time, otel.end_time = end_time ) .entered(); drop(span); } else { tracing::event!(name: "action_completed", Level::INFO, label = ?id.label); } } (Payload::Started(s), Id::Started(_)) => { assert!(spans .insert( "building", tracing::info_span!( "build_tool", version = ?s.build_tool_version, pid = ?s.server_pid, uuid = ?s.uuid, current_dir = ?s.working_directory, root_dir = ?s.workspace_directory, ) .entered() ) .is_none()); } (Payload::Finished(_), Id::BuildFinished(_)) => { spans .remove("building") .expect("build_finished should have been called after build_started") .exit(); } (Payload::Completed(target), Id::TargetCompleted(id)) => { tracing::event!( name: "target_completed", Level::INFO, label = id.label, aspect = id.aspect, success = target.success ); } _ => {} }; } }) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/stream/util.rs
crates/axl-runtime/src/engine/bazel/stream/util.rs
use std::io; use std::io::Read; use std::io::Result; pub const CONTINUATION_BIT: u8 = 1 << 7; #[inline] pub fn low_bits_of_byte(byte: u8) -> u8 { byte & !CONTINUATION_BIT } pub fn read_varint<T: Read>(stream: &mut T) -> Result<usize> { let mut result = 0; let mut shift = 0; loop { let mut buf = [0]; stream.read_exact(&mut buf)?; if shift == 63 && buf[0] != 0x00 && buf[0] != 0x01 { while buf[0] & CONTINUATION_BIT != 0 { stream.read_exact(&mut buf)?; } return Err(io::Error::new( io::ErrorKind::InvalidData, anyhow::anyhow!("variant overflow"), )); } let low_bits = low_bits_of_byte(buf[0]) as u64; result |= low_bits << shift; if buf[0] & CONTINUATION_BIT == 0 { return Ok(result as usize); } shift += 7; } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/stream/mod.rs
crates/axl-runtime/src/engine/bazel/stream/mod.rs
pub mod build_event; pub mod execlog; mod util; pub mod workspace_event; pub use build_event::BuildEventStream; pub use execlog::ExecLogStream; pub use workspace_event::WorkspaceEventStream;
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/stream/workspace_event.rs
crates/axl-runtime/src/engine/bazel/stream/workspace_event.rs
use axl_proto::workspace_log::WorkspaceEvent; use fibre::spmc::{bounded, Receiver}; use fibre::{CloseError, SendError}; use prost::Message; use std::fmt::Debug; use std::io::{self, ErrorKind, Read}; use std::path::PathBuf; use std::thread::JoinHandle; use std::{env, thread}; use thiserror::Error; use super::util::read_varint; #[derive(Error, Debug)] pub enum WorkspaceEventError { #[error("io error: {0}")] IO(#[from] std::io::Error), #[error("prost decode error: {0}")] ProstDecode(#[from] prost::DecodeError), #[error("send error: {0}")] Send(#[from] SendError), #[error("close error: {0}")] Close(#[from] CloseError), } pub struct WorkspaceEventStream { handle: JoinHandle<Result<(), WorkspaceEventError>>, recv: Receiver<WorkspaceEvent>, } impl Debug for WorkspaceEventStream { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("WorkspaceEventStream") .field("stream", &String::from("hidden")) .finish() } } impl WorkspaceEventStream { pub fn spawn_with_pipe(pid: u32) -> io::Result<(PathBuf, Self)> { let out = env::temp_dir().join(format!("workspace-event-out-{}.bin", uuid::Uuid::new_v4())); let stream = Self::spawn(out.clone(), pid)?; Ok((out, stream)) } pub fn spawn(path: PathBuf, pid: u32) -> io::Result<Self> { let (mut sender, recv) = bounded::<WorkspaceEvent>(1000); let handle: JoinHandle<Result<(), WorkspaceEventError>> = thread::spawn(move || { let mut buf: Vec<u8> = Vec::with_capacity(1024 * 5); // 10 is the maximum size of a varint so start with that size. buf.resize(10, 0); let mut out_raw = galvanize::Pipe::new(path.clone(), galvanize::RetryPolicy::IfOpenForPid(pid))?; let mut read = || -> Result<(), WorkspaceEventError> { // varint size can be somewhere between 1 to 10 bytes. let size = read_varint(&mut out_raw)?; if size > buf.len() { buf.resize(size, 0); } out_raw.read_exact(&mut buf[0..size])?; let event = WorkspaceEvent::decode(&buf[0..size])?; // Send blocks until there is room in the buffer. // https://docs.rs/fibre/latest/fibre/spmc/index.html sender.send(event)?; Ok(()) }; loop { let result = read(); // event decoding was succesfull move to the next. if result.is_ok() { continue; } match result.unwrap_err() { // this marks the end of the stream WorkspaceEventError::IO(err) if err.kind() == ErrorKind::BrokenPipe => { sender.close()?; return Ok(()); } err => return Err(err), } } }); Ok(Self { handle, recv }) } pub fn receiver(&self) -> Receiver<WorkspaceEvent> { self.recv.clone() } pub fn join(self) -> Result<(), WorkspaceEventError> { self.handle.join().expect("join error") } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/stream/build_event.rs
crates/axl-runtime/src/engine/bazel/stream/build_event.rs
use axl_proto::build_event_stream::BuildEvent; use fibre::spmc::{bounded, Receiver}; use fibre::{CloseError, SendError}; use prost::Message; use std::io::ErrorKind; use std::{env, io}; use std::{ io::Read, path::PathBuf, thread::{self, JoinHandle}, }; use thiserror::Error; use super::util::read_varint; #[derive(Error, Debug)] pub enum BuildEventStreamError { #[error("io error: {0}")] IO(#[from] std::io::Error), #[error("prost decode error: {0}")] ProstDecode(#[from] prost::DecodeError), #[error("send error: {0}")] Send(#[from] SendError), #[error("close error: {0}")] Close(#[from] CloseError), } #[derive(Debug)] pub struct BuildEventStream { handle: JoinHandle<Result<(), BuildEventStreamError>>, recv: Receiver<BuildEvent>, } impl BuildEventStream { pub fn spawn_with_pipe(pid: u32) -> io::Result<(PathBuf, Self)> { let out = env::temp_dir().join(format!("build-event-out-{}.bin", uuid::Uuid::new_v4())); let stream = Self::spawn(out.clone(), pid)?; Ok((out, stream)) } pub fn spawn(path: PathBuf, pid: u32) -> io::Result<Self> { let (mut sender, recv) = bounded::<BuildEvent>(1000); let handle = thread::spawn(move || { let mut buf: Vec<u8> = Vec::with_capacity(1024 * 5); // 10 is the maximum size of a varint so start with that size. buf.resize(10, 0); let mut out_raw = galvanize::Pipe::new(path.clone(), galvanize::RetryPolicy::IfOpenForPid(pid))?; let mut read = || -> Result<bool, BuildEventStreamError> { // varint size can be somewhere between 1 to 10 bytes. let size = read_varint(&mut out_raw)?; if size > buf.len() { buf.resize(size, 0); } out_raw.read_exact(&mut buf[0..size])?; let event = BuildEvent::decode(&buf[0..size])?; let last_message = event.last_message; // Send blocks until there is room in the buffer. // https://docs.rs/fibre/latest/fibre/spmc/index.html sender.send(event)?; Ok(last_message) }; loop { match read() { // marks the end of the stream Ok(last_message) if last_message => { sender.close()?; return Ok(()); } // marks the end of the stream Err(BuildEventStreamError::IO(err)) if err.kind() == ErrorKind::BrokenPipe => { sender.close()?; return Ok(()); } Ok(_) => continue, Err(err) => return Err(err), } } }); Ok(Self { handle, recv }) } pub fn receiver(&self) -> Receiver<BuildEvent> { self.recv.clone() } pub fn join(self) -> Result<(), BuildEventStreamError> { self.handle.join().expect("join error") } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/stream/execlog.rs
crates/axl-runtime/src/engine/bazel/stream/execlog.rs
use axl_proto::tools::protos::ExecLogEntry; use fibre::spmc::{bounded, Receiver}; use fibre::{CloseError, SendError}; use prost::Message; use std::fmt::Debug; use std::io; use std::io::Read; use std::path::PathBuf; use std::thread::JoinHandle; use std::{env, thread}; use thiserror::Error; use zstd::Decoder; use super::util::read_varint; #[derive(Error, Debug)] pub enum ExecLogStreamError { #[error("io error: {0}")] IO(#[from] std::io::Error), #[error("prost decode error: {0}")] ProstDecode(#[from] prost::DecodeError), #[error("send error: {0}")] Send(#[from] SendError), #[error("close error: {0}")] Close(#[from] CloseError), } #[derive(Debug)] pub struct ExecLogStream { handle: JoinHandle<Result<(), ExecLogStreamError>>, recv: Receiver<ExecLogEntry>, } impl ExecLogStream { pub fn spawn_with_pipe(pid: u32) -> io::Result<(PathBuf, Self)> { let out = env::temp_dir().join(format!("execlog-out-{}.bin", uuid::Uuid::new_v4())); let stream = Self::spawn(out.clone(), pid)?; Ok((out, stream)) } pub fn spawn(path: PathBuf, pid: u32) -> io::Result<Self> { let (mut sender, recv) = bounded::<ExecLogEntry>(1000); let handle = thread::spawn(move || { let mut buf: Vec<u8> = Vec::with_capacity(1024 * 5); // 10 is the maximum size of a varint so start with that size. buf.resize(10, 0); let out_raw = galvanize::Pipe::new(path.clone(), galvanize::RetryPolicy::IfOpenForPid(pid))?; let mut out_raw = Decoder::new(out_raw)?; let mut read = || -> Result<(), ExecLogStreamError> { // varint size can be somewhere between 1 to 10 bytes. let size = read_varint(&mut out_raw)?; if size > buf.len() { buf.resize(size, 0); } out_raw.read_exact(&mut buf[0..size])?; let entry = ExecLogEntry::decode(&buf[0..size])?; // Send blocks until there is room in the buffer. // https://docs.rs/fibre/latest/fibre/spmc/index.html sender.send(entry)?; Ok(()) }; loop { let result = read(); // event decoding was succesfull move to the next. if result.is_ok() { continue; } match result.unwrap_err() { // this marks the end of the stream ExecLogStreamError::IO(err) if err.kind() == io::ErrorKind::BrokenPipe => { sender.close()?; return Ok(()); } err => return Err(err), } } }); Ok(Self { handle, recv }) } pub fn receiver(&self) -> Receiver<ExecLogEntry> { self.recv.clone() } pub fn join(self) -> Result<(), ExecLogStreamError> { self.handle.join().expect("join error") } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/iter/mod.rs
crates/axl-runtime/src/engine/bazel/iter/mod.rs
mod build_event; mod execlog; mod workspace_event; pub use build_event::BuildEventIterator; pub use execlog::ExecutionLogIterator; pub use workspace_event::WorkspaceEventIterator;
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/iter/workspace_event.rs
crates/axl-runtime/src/engine/bazel/iter/workspace_event.rs
use std::cell::RefCell; use allocative::Allocative; use fibre::RecvError; use fibre::TryRecvError; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::starlark_module; use starlark::typing::Ty; use starlark::values; use starlark::values::none::NoneOr; use starlark::values::starlark_value; use starlark::values::AllocValue; use starlark::values::Heap; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::Trace; use starlark::values::ValueLike; use axl_proto::workspace_log::WorkspaceEvent; use derive_more::Display; use fibre::spmc::Receiver; #[derive(Debug, ProvidesStaticType, Display, Trace, NoSerialize, Allocative)] #[display("<workspace_event_iterator>")] pub struct WorkspaceEventIterator { #[allocative(skip)] recv: RefCell<Receiver<WorkspaceEvent>>, } impl WorkspaceEventIterator { pub fn new(recv: Receiver<WorkspaceEvent>) -> Self { Self { recv: RefCell::new(recv), } } } impl<'v> AllocValue<'v> for WorkspaceEventIterator { fn alloc_value(self, heap: &'v Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } } #[starlark_module] pub(crate) fn workspace_event_methods(registry: &mut MethodsBuilder) { /// Returns `WorkspaceEvent` if event buffer is not empty. /// Maximum `1000` events is buffered at once. fn try_pop<'v>(this: values::Value<'v>) -> anyhow::Result<NoneOr<WorkspaceEvent>> { let this = this.downcast_ref_err::<WorkspaceEventIterator>()?; match this.recv.borrow_mut().try_recv() { Ok(it) => Ok(NoneOr::Other(it)), Err(TryRecvError::Empty) => Ok(NoneOr::None), Err(TryRecvError::Disconnected) => Ok(NoneOr::None), } } /// Returns `True` if stream is complete and all the events are received via `for` /// or calling `pop` repeatedly. fn done<'v>(this: values::Value<'v>) -> anyhow::Result<bool> { let this = this.downcast_ref_err::<WorkspaceEventIterator>()?; Ok(this.recv.borrow().is_closed()) } } #[starlark_value(type = "BuildEventIterator")] impl<'v> values::StarlarkValue<'v> for WorkspaceEventIterator { fn eval_type(&self) -> Option<Ty> { Some(Ty::iter(WorkspaceEvent::get_type_starlark_repr())) } fn get_type_starlark_repr() -> Ty { Ty::iter(WorkspaceEvent::get_type_starlark_repr()) } fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(workspace_event_methods) } unsafe fn iterate( &self, me: values::Value<'v>, _heap: &'v Heap, ) -> starlark::Result<values::Value<'v>> { Ok(me) } unsafe fn iter_next(&self, _index: usize, heap: &'v Heap) -> Option<values::Value<'v>> { match self.recv.borrow_mut().recv() { Ok(ev) => Some(ev.alloc_value(heap)), Err(RecvError::Disconnected) => None, } } unsafe fn iter_stop(&self) {} }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/iter/build_event.rs
crates/axl-runtime/src/engine/bazel/iter/build_event.rs
use std::cell::RefCell; use allocative::Allocative; use fibre::RecvError; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::starlark_module; use starlark::typing::Ty; use starlark::values; use starlark::values::none::NoneOr; use starlark::values::starlark_value; use starlark::values::AllocValue; use starlark::values::Heap; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::Trace; use starlark::values::ValueLike; use axl_proto::build_event_stream::BuildEvent; use derive_more::Display; use fibre::spmc::Receiver; #[derive(Debug, ProvidesStaticType, Display, Trace, NoSerialize, Allocative)] #[display("<build_event_iterator>")] pub struct BuildEventIterator { #[allocative(skip)] recv: RefCell<Receiver<BuildEvent>>, } impl BuildEventIterator { pub fn new(recv: Receiver<BuildEvent>) -> Self { Self { recv: RefCell::new(recv), } } } impl<'v> AllocValue<'v> for BuildEventIterator { fn alloc_value(self, heap: &'v Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } } #[starlark_module] pub(crate) fn build_event_methods(registry: &mut MethodsBuilder) { /// Returns `BuildEvent` if event buffer is not empty. /// Maximum `1000` events is buffered at once. fn try_pop<'v>(this: values::Value<'v>) -> anyhow::Result<NoneOr<BuildEvent>> { let this = this.downcast_ref_err::<BuildEventIterator>()?; match this.recv.borrow_mut().try_recv() { Ok(it) => Ok(NoneOr::Other(it)), Err(_) => Ok(NoneOr::None), } } /// Returns `True` if stream is complete and all the events are received via `for` /// or calling `try_pop` repeatedly. fn done<'v>(this: values::Value<'v>) -> anyhow::Result<bool> { let this = this.downcast_ref_err::<BuildEventIterator>()?; Ok(this.recv.borrow().is_closed()) } } #[starlark_value(type = "BuildEventIterator")] impl<'v> values::StarlarkValue<'v> for BuildEventIterator { fn eval_type(&self) -> Option<Ty> { Some(Ty::iter(BuildEvent::get_type_starlark_repr())) } fn get_type_starlark_repr() -> Ty { Ty::iter(BuildEvent::get_type_starlark_repr()) } fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(build_event_methods) } unsafe fn iterate( &self, me: values::Value<'v>, _heap: &'v Heap, ) -> starlark::Result<values::Value<'v>> { Ok(me) } unsafe fn iter_next(&self, _index: usize, heap: &'v Heap) -> Option<values::Value<'v>> { match self.recv.borrow_mut().recv() { Ok(ev) => Some(ev.alloc_value(heap)), Err(RecvError::Disconnected) => None, } } unsafe fn iter_stop(&self) {} }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/bazel/iter/execlog.rs
crates/axl-runtime/src/engine/bazel/iter/execlog.rs
use std::cell::RefCell; use allocative::Allocative; use fibre::RecvError; use fibre::TryRecvError; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::starlark_module; use starlark::typing::Ty; use starlark::values; use starlark::values::none::NoneOr; use starlark::values::starlark_value; use starlark::values::AllocValue; use starlark::values::Heap; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::Trace; use starlark::values::ValueLike; use axl_proto::tools::protos::ExecLogEntry; use derive_more::Display; use fibre::spmc::Receiver; #[derive(ProvidesStaticType, Display, Trace, NoSerialize, Allocative, Debug)] #[display("<execlog_iterator>")] pub struct ExecutionLogIterator { #[allocative(skip)] recv: RefCell<Receiver<ExecLogEntry>>, } impl ExecutionLogIterator { pub fn new(recv: Receiver<ExecLogEntry>) -> Self { Self { recv: RefCell::new(recv), } } } impl<'v> AllocValue<'v> for ExecutionLogIterator { fn alloc_value(self, heap: &'v Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } } #[starlark_module] pub(crate) fn execlog_methods(registry: &mut MethodsBuilder) { /// Returns `ExecLogEntry` if event buffer is not empty. /// Maximum `1000` events is buffered at once. fn try_pop<'v>(this: values::Value<'v>) -> anyhow::Result<NoneOr<ExecLogEntry>> { let this = this.downcast_ref_err::<ExecutionLogIterator>()?; match this.recv.borrow_mut().try_recv() { Ok(it) => Ok(NoneOr::Other(it)), Err(TryRecvError::Empty) => Ok(NoneOr::None), Err(TryRecvError::Disconnected) => Ok(NoneOr::None), } } /// Returns `True` if stream is complete and all the events are received via `for` /// or calling `try_pop` repeatedly. fn done<'v>(this: values::Value<'v>) -> anyhow::Result<bool> { let this = this.downcast_ref_err::<ExecutionLogIterator>()?; Ok(this.recv.borrow().is_closed()) } } #[starlark_value(type = "ExecutionLogIterator")] impl<'v> values::StarlarkValue<'v> for ExecutionLogIterator { fn eval_type(&self) -> Option<Ty> { Some(Ty::iter(ExecLogEntry::get_type_starlark_repr())) } fn get_type_starlark_repr() -> Ty { Ty::iter(ExecLogEntry::get_type_starlark_repr()) } fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(execlog_methods) } unsafe fn iterate( &self, me: values::Value<'v>, _heap: &'v Heap, ) -> starlark::Result<values::Value<'v>> { Ok(me) } unsafe fn iter_next(&self, _index: usize, heap: &'v Heap) -> Option<values::Value<'v>> { match self.recv.borrow_mut().recv() { Ok(ev) => Some(ev.alloc_value(heap)), Err(RecvError::Disconnected) => None, } } unsafe fn iter_stop(&self) {} }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/template/liquid.rs
crates/axl-runtime/src/engine/template/liquid.rs
use liquid::ParserBuilder as LiquidParserBuilder; use liquid_core::model::{KString, Object as LiquidObject, Value as LiquidValue}; use serde_json::Value as JsonValue; pub(super) fn liquid_render(template: &str, data: &JsonValue) -> anyhow::Result<String> { fn json_to_liquid(json: &JsonValue) -> LiquidValue { match json { JsonValue::Null => LiquidValue::Nil, JsonValue::Bool(b) => LiquidValue::scalar(*b), JsonValue::Number(n) => { if let Some(i) = n.as_i64() { LiquidValue::scalar(i) } else { LiquidValue::scalar(n.as_f64().unwrap()) } } JsonValue::String(s) => LiquidValue::scalar(s.as_str()), JsonValue::Array(arr) => { LiquidValue::array(arr.iter().map(json_to_liquid).collect::<Vec<_>>()) } JsonValue::Object(obj) => { let mut liquid_obj = LiquidObject::new(); for (k, v) in obj.iter() { liquid_obj.insert(KString::from_ref(k), json_to_liquid(v)); } LiquidValue::object(liquid_obj) } } } let parser = LiquidParserBuilder::with_stdlib() .build() .map_err(|e| anyhow::anyhow!(e))?; let template = parser.parse(template).map_err(|e| anyhow::anyhow!(e))?; let globals = if let LiquidValue::Object(obj) = json_to_liquid(data) { obj } else { return Err(anyhow::anyhow!("data is not an object")); }; template.render(&globals).map_err(|e| anyhow::anyhow!(e)) }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/template/jinja2.rs
crates/axl-runtime/src/engine/template/jinja2.rs
use minijinja::{value::Value as MinijinjaValue, Environment as MinijinjaEnvironment}; use serde_json::Value as JsonValue; pub(super) fn jinja2_render(template: &str, data: &JsonValue) -> anyhow::Result<String> { let mut env = MinijinjaEnvironment::new(); env.add_template("template", template) .map_err(|e| anyhow::anyhow!(e))?; let tmpl = env .get_template("template") .map_err(|e| anyhow::anyhow!(e))?; let ctx = MinijinjaValue::from_serialize(data).map_err(|e| anyhow::anyhow!(e))?; tmpl.render(&ctx).map_err(|e| anyhow::anyhow!(e)) }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/template/mod.rs
crates/axl-runtime/src/engine/template/mod.rs
mod handlebars; // mod jinja2; // mod liquid; use allocative::Allocative; use derive_more::Display; use serde_json::{Map, Value as JsonValue}; use starlark::environment::{Methods, MethodsBuilder, MethodsStatic}; use starlark::starlark_module; use starlark::starlark_simple_value; use starlark::values::dict::UnpackDictEntries; use starlark::values::StringValue; use starlark::values::{starlark_value, NoSerialize, ProvidesStaticType, StarlarkValue, Value}; use crate::engine::template::handlebars::handlebars_render; // use crate::engine::template::jinja2::jinja2_render; // use crate::engine::template::liquid::liquid_render; use liquid::ParserBuilder as LiquidParserBuilder; use liquid_core::model::{KString, Object as LiquidObject, Value as LiquidValue}; use minijinja::{value::Value as MinijinjaValue, Environment as MinijinjaEnvironment}; pub(super) fn jinja2_render(template: &str, data: &JsonValue) -> anyhow::Result<String> { let mut env = MinijinjaEnvironment::new(); env.add_template("template", template) .map_err(|e| anyhow::anyhow!(e))?; let tmpl = env .get_template("template") .map_err(|e| anyhow::anyhow!(e))?; let ctx = MinijinjaValue::from_serialize(data); tmpl.render(&ctx).map_err(|e| anyhow::anyhow!(e)) } fn liquid_render(template: &str, data: &JsonValue) -> anyhow::Result<String> { fn json_to_liquid(json: &JsonValue) -> LiquidValue { match json { JsonValue::Null => LiquidValue::Nil, JsonValue::Bool(b) => LiquidValue::scalar(*b), JsonValue::Number(n) => { if let Some(i) = n.as_i64() { LiquidValue::scalar(i) } else { LiquidValue::scalar(n.as_f64().unwrap()) } } JsonValue::String(s) => LiquidValue::scalar(s.to_string()), JsonValue::Array(arr) => { LiquidValue::array(arr.iter().map(json_to_liquid).collect::<Vec<_>>()) } JsonValue::Object(obj) => { let mut liquid_obj = LiquidObject::new(); for (k, v) in obj.iter() { liquid_obj.insert(KString::from_ref(k.as_str()), json_to_liquid(v)); } LiquidValue::Object(liquid_obj) } } } let parser = LiquidParserBuilder::with_stdlib() .build() .map_err(|e| anyhow::anyhow!(e))?; let template = parser.parse(template).map_err(|e| anyhow::anyhow!(e))?; let globals = if let LiquidValue::Object(obj) = json_to_liquid(data) { obj } else { return Err(anyhow::anyhow!("data is not an object")); }; template.render(&globals).map_err(|e| anyhow::anyhow!(e)) } #[derive(Debug, Display, ProvidesStaticType, NoSerialize, Allocative)] #[display("<Template>")] pub struct Template {} impl Template { pub fn new() -> Self { Self {} } } starlark_simple_value!(Template); #[starlark_value(type = "Template")] impl<'v> StarlarkValue<'v> for Template { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(template_methods) } } #[starlark_module] pub(crate) fn template_methods(registry: &mut MethodsBuilder) { /// Renders a Handlebars template with the provided data. /// /// **Parameters** /// - `template`: The Handlebars template string. /// - `data`: A dictionary of data to render the template with. /// /// **Returns** /// The rendered template as a string. /// /// **Example** /// ```starlark /// result = ctx.template.handlebars("Hello, {{name}}!", {"name": "World"}) /// ``` fn handlebars<'v>( #[allow(unused)] this: Value<'v>, #[starlark(require = pos)] template: StringValue<'v>, #[starlark(require = named, default = UnpackDictEntries::default())] data: UnpackDictEntries<String, Value<'v>>, ) -> anyhow::Result<String> { let mut json_map: Map<String, JsonValue> = Map::new(); for (k, v) in data.entries { json_map.insert(k, v.to_json_value()?); } let json_data = JsonValue::Object(json_map); handlebars_render(template.as_str(), &json_data) } /// Renders a Jinja2 template with the provided data. /// /// **Parameters** /// - `template`: The Jinja2 template string. /// - `data`: A dictionary of data to render the template with. /// /// **Returns** /// The rendered template as a string. /// /// **Example** /// ```starlark /// result = ctx.template.jinja2("Hello, {{ name }}!", {"name": "World"}) /// ``` fn jinja2<'v>( #[allow(unused)] this: Value<'v>, #[starlark(require = pos)] template: StringValue<'v>, #[starlark(require = named, default = UnpackDictEntries::default())] data: UnpackDictEntries<String, Value<'v>>, ) -> anyhow::Result<String> { let mut json_map: Map<String, JsonValue> = Map::new(); for (k, v) in data.entries { json_map.insert(k, v.to_json_value()?); } let json_data = JsonValue::Object(json_map); jinja2_render(template.as_str(), &json_data) } /// Renders a Liquid template with the provided data. /// /// **Parameters** /// - `template`: The Liquid template string. /// - `data`: A dictionary of data to render the template with. /// /// **Returns** /// The rendered template as a string. /// /// **Example** /// ```starlark /// result = ctx.template.liquid("Hello, {{ name }}!", {"name": "World"}) /// ``` fn liquid<'v>( #[allow(unused)] this: Value<'v>, #[starlark(require = pos)] template: StringValue<'v>, #[starlark(require = named, default = UnpackDictEntries::default())] data: UnpackDictEntries<String, Value<'v>>, ) -> anyhow::Result<String> { let mut json_map: Map<String, JsonValue> = Map::new(); for (k, v) in data.entries { json_map.insert(k, v.to_json_value()?); } let json_data = JsonValue::Object(json_map); liquid_render(template.as_str(), &json_data) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/template/handlebars.rs
crates/axl-runtime/src/engine/template/handlebars.rs
use handlebars::Handlebars; use serde_json::Value as JsonValue; pub(super) fn handlebars_render(template: &str, data: &JsonValue) -> anyhow::Result<String> { let hb = Handlebars::new(); let rendered = hb.render_template(template, data)?; Ok(rendered) }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/config/mod.rs
crates/axl-runtime/src/engine/config/mod.rs
mod context; mod task_list; pub use context::ConfigContext; pub use task_list::task_mut::TaskMut;
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/config/context.rs
crates/axl-runtime/src/engine/config/context.rs
use std::cell::RefCell; use allocative::Allocative; use derive_more::Display; use starlark::environment::FrozenModule; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::starlark_module; use starlark::values; use starlark::values::starlark_value; use starlark::values::AllocValue; use starlark::values::Heap; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::Trace; use starlark::values::ValueLike; use starlark::values::ValueOfUnchecked; use crate::engine::config::task_list::value::MutableTaskList; use crate::engine::config::task_list::value::TaskListGen; use super::super::http::Http; use super::super::std::Std; use super::super::template; use super::super::wasm::Wasm; use super::task_list::r#ref::TaskListRef; use super::task_list::task_mut::TaskMut; use super::task_list::value::TaskList; #[derive(Debug, Clone, ProvidesStaticType, Trace, Display, NoSerialize, Allocative)] #[display("<ConfigContext>")] pub struct ConfigContext<'v> { #[allocative(skip)] tasks: values::Value<'v>, #[allocative(skip)] config_modules: RefCell<Vec<FrozenModule>>, } impl<'v> ConfigContext<'v> { pub fn new(tasks: Vec<TaskMut<'v>>, heap: &'v Heap) -> Self { let tasks: Vec<values::Value<'v>> = tasks .into_iter() .map(|task| task.alloc_value(heap)) .collect(); let x = TaskListGen(RefCell::new(TaskList::new(tasks))); Self { tasks: heap.alloc_complex_no_freeze(x), config_modules: RefCell::new(vec![]), } } pub fn tasks(&'v self) -> Vec<&'v TaskMut<'v>> { let list = self.tasks.downcast_ref::<MutableTaskList>().unwrap(); list.0 .borrow() .content .iter() .map(|m| m.downcast_ref::<TaskMut>().unwrap()) .collect() } pub fn add_config_module(&self, module: FrozenModule) { self.config_modules.borrow_mut().push(module); } } #[starlark_value(type = "ConfigContext")] impl<'v> values::StarlarkValue<'v> for ConfigContext<'v> { fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(config_context_methods) } } impl<'v> values::AllocValue<'v> for ConfigContext<'v> { fn alloc_value(self, heap: &'v values::Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } } impl<'v> values::Freeze for ConfigContext<'v> { type Frozen = ConfigContext<'v>; fn freeze(self, _freezer: &values::Freezer) -> values::FreezeResult<Self::Frozen> { panic!("not implemented") } } #[starlark_module] pub(crate) fn config_context_methods(registry: &mut MethodsBuilder) { /// Standard library is the foundation of powerful AXL tasks. #[starlark(attribute)] fn std<'v>(#[allow(unused)] this: values::Value<'v>) -> starlark::Result<Std> { Ok(Std {}) } /// Expand template files. #[starlark(attribute)] fn template<'v>( #[allow(unused)] this: values::Value<'v>, ) -> starlark::Result<template::Template> { Ok(template::Template::new()) } /// EXPERIMENTAL! Run wasm programs within tasks. #[starlark(attribute)] fn wasm<'v>(#[allow(unused)] this: values::Value<'v>) -> starlark::Result<Wasm> { Ok(Wasm::new()) } /// The `http` attribute provides a programmatic interface for making HTTP requests. /// It is used to fetch data from remote servers and can be used in conjunction with /// other aspects to perform complex data processing tasks. /// /// **Example** /// /// ```starlark /// **Fetch** data from a remote server /// data = ctx.http().get("https://example.com/data.json").block() /// ``` fn http<'v>(#[allow(unused)] this: values::Value<'v>) -> starlark::Result<Http> { Ok(Http::new()) } #[starlark(attribute)] fn tasks<'v>( #[allow(unused)] this: values::Value<'v>, ) -> anyhow::Result<ValueOfUnchecked<'v, &'v TaskListRef<'v>>> { let this = this.downcast_ref_err::<ConfigContext>()?; Ok(ValueOfUnchecked::new(this.tasks)) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/config/task_list/ref.rs
crates/axl-runtime/src/engine/config/task_list/ref.rs
use std::{ cell::{Ref, RefCell, RefMut}, convert::Infallible, ops::Deref, }; use dupe::Dupe; use either::Either; use starlark::{ typing::Ty, values::{type_repr::StarlarkTypeRepr, UnpackValue, Value, ValueError, ValueLike}, }; use super::value::{TaskList, TaskListGen}; /// Borrowed `TaskList`. #[derive(Debug)] pub struct TaskListRef<'v> { pub(crate) aref: Either<Ref<'v, TaskList<'v>>, &'v TaskList<'v>>, } impl<'v> Clone for TaskListRef<'v> { fn clone(&self) -> Self { match &self.aref { Either::Left(x) => TaskListRef { aref: Either::Left(Ref::clone(x)), }, Either::Right(x) => TaskListRef { aref: Either::Right(*x), }, } } } impl<'v> Dupe for TaskListRef<'v> {} /// Mutably borrowed `TaskListata`. pub struct TaskListMut<'v> { pub(crate) aref: RefMut<'v, TaskList<'v>>, } impl<'v> TaskListRef<'v> { /// Downcast the value to a TaskListata. pub fn from_value(x: Value<'v>) -> Option<TaskListRef<'v>> { let ptr = x.downcast_ref::<TaskListGen<RefCell<TaskList<'v>>>>()?; Some(TaskListRef { aref: Either::Left(ptr.0.borrow()), }) } } impl<'v> StarlarkTypeRepr for &'v TaskListRef<'v> { type Canonical = <Vec<Value<'v>> as StarlarkTypeRepr>::Canonical; fn starlark_type_repr() -> Ty { Vec::<Value<'v>>::starlark_type_repr() } } impl<'v> TaskListMut<'v> { /// Downcast the value to a mutable TaskListata reference. #[inline] pub fn from_value(x: Value<'v>) -> anyhow::Result<TaskListMut<'v>> { #[derive(thiserror::Error, Debug)] #[error("Value is not TaskListData, value type: `{0}`")] struct NotTaskListDataError(&'static str); let ptr = x.downcast_ref::<TaskListGen<RefCell<TaskList<'v>>>>(); match ptr { None => Err(NotTaskListDataError(x.get_type()).into()), Some(ptr) => match ptr.0.try_borrow_mut() { Ok(x) => Ok(TaskListMut { aref: x }), Err(_) => Err(ValueError::MutationDuringIteration.into()), }, } } } impl<'v> Deref for TaskListRef<'v> { type Target = TaskList<'v>; fn deref(&self) -> &Self::Target { &self.aref } } impl<'v> StarlarkTypeRepr for TaskListRef<'v> { type Canonical = Self; fn starlark_type_repr() -> Ty { Ty::any() } } impl<'v> UnpackValue<'v> for TaskListRef<'v> { type Error = Infallible; fn unpack_value_impl(value: Value<'v>) -> Result<Option<TaskListRef<'v>>, Infallible> { Ok(TaskListRef::from_value(value)) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/config/task_list/value.rs
crates/axl-runtime/src/engine/config/task_list/value.rs
use std::cell::RefCell; use std::fmt; use std::fmt::Debug; use std::fmt::Display; use allocative::Allocative; use starlark::any::ProvidesStaticType; use starlark::environment::Methods; use starlark::environment::MethodsBuilder; use starlark::environment::MethodsStatic; use starlark::eval::Evaluator; use starlark::starlark_module; use starlark::typing::Ty; use starlark::values::none::NoneType; use starlark::values::starlark_value; use starlark::values::type_repr::StarlarkTypeRepr; use starlark::values::AllocValue; use starlark::values::Heap; use starlark::values::NoSerialize; use starlark::values::StarlarkValue; use starlark::values::Trace; use starlark::values::Value; use starlark::values::ValueLike; use super::r#ref::TaskListMut; use super::task_mut::TaskMut; use crate::engine::store::AxlStore; use crate::engine::task::{AsTaskLike, FrozenTask, Task, TaskLike}; #[derive(Clone, Default, Trace, Debug, ProvidesStaticType, NoSerialize, Allocative)] pub(crate) struct TaskListGen<T>(pub(crate) T); impl<'v, T: TaskListLike<'v>> Display for TaskListGen<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "tasks") } } #[starlark_module] pub(crate) fn task_list_methods(registry: &mut MethodsBuilder) { fn add<'v>( #[allow(unused)] this: Value<'v>, #[starlark(require = pos)] task: Value<'v>, eval: &mut Evaluator<'v, '_, '_>, ) -> starlark::Result<NoneType> { let store = AxlStore::from_eval(eval)?; let mut this = TaskListMut::from_value(this)?; let symbol = format!("__added_task_{}", this.aref.content.len()); eval.module().set(&symbol, task); let task_like: &dyn TaskLike = if let Some(t) = task.downcast_ref::<Task>() { t.as_task() } else if let Some(t) = task.downcast_ref::<FrozenTask>() { t.as_task() } else { return Err(anyhow::anyhow!( "expected value of type 'Task', got '{}'", task.get_type() ) .into()); }; let name = task_like.name().to_owned(); if name.len() == 0 { return Err(anyhow::anyhow!("Task name required").into()); } this.aref.content.push(eval.heap().alloc(TaskMut::new( &eval.module(), symbol, store.script_path.to_string_lossy().to_string(), name, task_like.group().to_vec(), ))); Ok(NoneType) } } #[starlark_value(type = "tasks")] impl<'v, T: TaskListLike<'v> + 'v> StarlarkValue<'v> for TaskListGen<T> where Self: ProvidesStaticType<'v>, { type Canonical = Self; fn get_methods() -> Option<&'static Methods> { static RES: MethodsStatic = MethodsStatic::new(); RES.methods(task_list_methods) } fn iterate_collect(&self, heap: &'v Heap) -> starlark::Result<Vec<Value<'v>>> { self.0.iterate_collect(heap) } } pub(crate) type MutableTaskList<'v> = TaskListGen<RefCell<TaskList<'v>>>; /// Unfrozen TaskList #[derive(Clone, Trace, Debug, ProvidesStaticType, Allocative)] #[repr(transparent)] pub struct TaskList<'v> { pub(crate) content: Vec<Value<'v>>, } impl<'v> TaskList<'v> { pub fn new(content: Vec<Value<'v>>) -> Self { return TaskList { content }; } } impl<'v> Display for TaskList<'v> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "tasks") } } impl<'v> StarlarkTypeRepr for TaskList<'v> { type Canonical = Self; fn starlark_type_repr() -> Ty { Ty::any() } } impl<'v> AllocValue<'v> for TaskList<'v> { fn alloc_value(self, heap: &'v Heap) -> Value<'v> { heap.alloc_complex_no_freeze(TaskListGen(RefCell::new(self))) } } trait TaskListLike<'v>: Debug + Allocative { fn iterate_collect(&self, _heap: &'v Heap) -> starlark::Result<Vec<Value<'v>>>; } impl<'v> TaskListLike<'v> for RefCell<TaskList<'v>> { fn iterate_collect(&self, _heap: &'v Heap) -> starlark::Result<Vec<Value<'v>>> { Ok(self .borrow() .content .iter() .map(|f| f.to_value()) .collect::<Vec<Value<'v>>>()) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/config/task_list/task_mut.rs
crates/axl-runtime/src/engine/config/task_list/task_mut.rs
use std::cell::RefCell; use std::path::PathBuf; use allocative::Allocative; use anyhow::anyhow; use derive_more::Display; use starlark::environment::FrozenModule; use starlark::environment::Module; use starlark::values; use starlark::values::list::AllocList; use starlark::values::list::UnpackList; use starlark::values::starlark_value; use starlark::values::Heap; use starlark::values::NoSerialize; use starlark::values::ProvidesStaticType; use starlark::values::Trace; use starlark::values::UnpackValue; use starlark::values::Value; use starlark::values::ValueError; use starlark::values::ValueLike; use crate::engine::task::AsTaskLike; use crate::engine::task::FrozenTask; use crate::engine::task::Task; use crate::engine::task::TaskLike; #[derive(Debug, Clone, ProvidesStaticType, Display, NoSerialize, Allocative)] #[display("<TaskMut>")] pub struct TaskMut<'v> { pub name: RefCell<String>, pub group: RefCell<Vec<String>>, pub config: RefCell<Value<'v>>, pub symbol: String, pub path: PathBuf, #[allocative(skip)] pub module: &'v Module, #[allocative(skip)] pub frozen_config_module: RefCell<Option<FrozenModule>>, } unsafe impl<'v> Trace<'v> for TaskMut<'v> { fn trace(&mut self, tracer: &values::Tracer<'v>) { tracer.trace(&mut *self.config.borrow_mut()); } } impl<'v> TaskMut<'v> { pub fn new( module: &'v Module, symbol: String, path: String, name: String, group: Vec<String>, ) -> Self { TaskMut { name: RefCell::new(name), group: RefCell::new(group), config: RefCell::new(Value::new_none()), symbol, path: PathBuf::from(path), module, frozen_config_module: RefCell::new(None), } } pub fn as_task(&'v self) -> Option<&'v dyn TaskLike<'v>> { let original = self .module .get(&self.symbol) .expect("symbol should have been defined."); if let Some(task) = original.downcast_ref::<Task<'v>>() { return Some(task.as_task()); } else if let Some(task) = original.downcast_ref::<FrozenTask>() { return Some(task.as_task()); } else { return None; } } pub fn initial_config(&self) -> Value<'v> { let original = self .module .get(&self.symbol) .expect("symbol should have been defined."); if let Some(task) = original.downcast_ref::<Task<'v>>() { task.config } else if let Some(task) = original.downcast_ref::<FrozenTask>() { task.config.to_value() } else { Value::new_none() } } } #[starlark_value(type = "TaskMut")] impl<'v> values::StarlarkValue<'v> for TaskMut<'v> { fn set_attr(&self, attribute: &str, value: values::Value<'v>) -> starlark::Result<()> { match attribute { "name" => { self.name.replace(value.to_str()); } "group" => { let unpack: UnpackList<String> = UnpackList::unpack_value(value)? .ok_or(anyhow!("groups must be a list of strings"))?; self.group.replace(unpack.items); } "config" => { // Use a frozen version of the config value passed in so that it can be safely referenced across // Starlark modules as the value is set in the config module but will used by the task that owns // the config which is most often in a different module. let temp_module = Module::new(); let short_value: Value = unsafe { std::mem::transmute(value) }; temp_module.set("temp", short_value); let frozen = temp_module.freeze().expect("freeze failed"); let frozen_val: Value<'v> = unsafe { std::mem::transmute(frozen.get("temp").expect("get").value()) }; self.config.replace(frozen_val); // Store the frozen module so the frozen heap that backs the config value is not lost. *self.frozen_config_module.borrow_mut() = Some(frozen); } _ => return ValueError::unsupported(self, &format!(".{}=", attribute)), }; Ok(()) } fn get_attr(&self, attribute: &str, heap: &'v Heap) -> Option<values::Value<'v>> { match attribute { "name" => Some(heap.alloc_str(self.name.borrow().as_str()).to_value()), "group" => Some(heap.alloc(AllocList(self.group.borrow().iter()))), "config" => Some(*self.config.borrow()), _ => None, } } fn dir_attr(&self) -> Vec<String> { vec![ "group".into(), "name".into(), "args".into(), "config".into(), ] } } impl<'v> values::AllocValue<'v> for TaskMut<'v> { fn alloc_value(self, heap: &'v values::Heap) -> values::Value<'v> { heap.alloc_complex_no_freeze(self) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-runtime/src/engine/config/task_list/mod.rs
crates/axl-runtime/src/engine/config/task_list/mod.rs
pub mod r#ref; pub mod task_mut; pub mod value;
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/aspect-launcher/src/config.rs
crates/aspect-launcher/src/config.rs
use std::env::current_dir; use std::path::{Path, PathBuf}; use std::{collections::HashMap, fmt::Debug, fs}; use aspect_telemetry::cargo_pkg_short_version; use miette::{miette, Result}; use serde::Deserialize; const AXL_MODULE_FILE: &str = "MODULE.aspect"; #[derive(Debug, Clone)] pub struct AspectLauncherConfig { pub aspect_cli: AspectCliConfig, } #[derive(Deserialize, Debug, Clone)] struct RawAspectConfig { #[serde(rename = "aspect-cli")] pub aspect_cli: Option<AspectCliConfig>, } fn default_cli_sources() -> Vec<ToolSource> { vec![{ ToolSource::GitHub { org: "aspect-build".into(), repo: "aspect-cli".into(), release: "v{{ version }}".into(), artifact: "aspect-cli-{{ llvm_triple }}".into(), } }] } #[derive(Deserialize, Debug, Clone)] pub struct AspectCliConfig { #[serde(default = "default_cli_sources")] sources: Vec<ToolSource>, #[serde(default = "cargo_pkg_short_version")] version: String, } #[derive(Deserialize, Debug, Clone)] #[serde(untagged)] pub enum ToolSource { GitHub { org: String, repo: String, release: String, artifact: String, }, Http { url: String, #[serde(default = "HashMap::new")] headers: HashMap<String, String>, }, Local { path: String, }, } pub trait ToolSpec: Debug { fn name(&self) -> String; fn version(&self) -> &String; fn sources(&self) -> &Vec<ToolSource>; } impl ToolSpec for AspectCliConfig { fn name(&self) -> String { "aspect-cli".to_owned() } fn sources(&self) -> &Vec<ToolSource> { &self.sources } fn version(&self) -> &String { &self.version } } pub fn load_config(path: &PathBuf) -> Result<AspectLauncherConfig> { let content = match fs::read_to_string(path) { Ok(c) => c, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(default_config()), Err(e) => return Err(miette!("failed to read config file {:?}: {}", path, e)), }; let raw: RawAspectConfig = match toml::from_str(&content) { Ok(config) => config, Err(e) => return Err(miette!("failed to parse config file {:?}: {}", path, e)), }; let config = AspectLauncherConfig { aspect_cli: raw.aspect_cli.unwrap_or_else(default_aspect_cli_config), }; Ok(config) } fn default_aspect_cli_config() -> AspectCliConfig { AspectCliConfig { sources: default_cli_sources(), version: cargo_pkg_short_version(), } } pub fn default_config() -> AspectLauncherConfig { AspectLauncherConfig { aspect_cli: default_aspect_cli_config(), } } /// Automatically determines the project root directory and loads the Aspect configuration. /// /// The root dir is identified as the first (deepest) ancestor directory of the current working /// directory that contains at least one of the following boundary files: MODULE.aspect, MODULE.bazel, /// MODULE.bazel.lock, REPO.bazel, WORKSPACE, or WORKSPACE.bazel. If no such directory is found, the /// current working directory is used as the project root. /// /// It then constructs the path to `.aspect/config.toml` within the project root directory and loads the /// configuration using `load_config`. /// /// **Returns** /// /// A `Result` containing a tuple `(PathBuf, AspectLauncherConfig)` where: /// - The first element is the determined root directory. /// - The second element is the loaded `AspectLauncherConfig`. /// /// **Errors** /// /// Returns an error if the current working directory cannot be obtained or if loading the config fails. pub fn autoconf() -> Result<(PathBuf, AspectLauncherConfig)> { let current_dir = current_dir().map_err(|e| miette!("failed to get current directory: {}", e))?; let root_dir = if let Some(repo_root) = current_dir .ancestors() .filter(|dir| { dir.join(PathBuf::from(AXL_MODULE_FILE)).exists() // Repository boundary marker files: https://bazel.build/external/overview#repository || dir.join(PathBuf::from("MODULE.bazel")).exists() || dir.join(PathBuf::from("MODULE.bazel.lock")).exists() || dir.join(PathBuf::from("REPO.bazel")).exists() || dir.join(PathBuf::from("WORKSPACE")).exists() || dir.join(PathBuf::from("WORKSPACE.bazel")).exists() }) .next() .map(Path::to_path_buf) { repo_root } else { current_dir }; let config_toml = root_dir .join(PathBuf::from(".aspect/config.toml")) .to_path_buf(); let config = load_config(&config_toml)?; Ok((root_dir, config)) }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/aspect-launcher/src/main.rs
crates/aspect-launcher/src/main.rs
mod cache; mod config; use std::collections::HashMap; use std::env; use std::env::var; use std::fs; use std::fs::File; use std::io::{self, Write}; use std::os::unix::fs::PermissionsExt; use std::os::unix::process::CommandExt; use std::path::PathBuf; use std::process::Command as UnixCommand; use std::process::ExitCode; use std::str::FromStr; use aspect_telemetry::{ cargo_pkg_short_version, do_not_track, send_telemetry, BZLARCH, BZLOS, GOARCH, GOOS, LLVM_TRIPLE, }; use clap::{arg, Arg, Command}; use fork::{fork, Fork}; use futures_util::TryStreamExt; use miette::{miette, Context, IntoDiagnostic, Result}; use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; use reqwest::{self, Client, Method, Request, RequestBuilder}; use serde::Deserialize; use tokio::runtime; use tokio::task::{self, JoinHandle}; use crate::cache::AspectCache; use crate::config::{autoconf, ToolSource, ToolSpec}; fn debug_mode() -> bool { match var("ASPECT_DEBUG") { Ok(val) => !val.is_empty(), _ => false, } } const ASPECT_LAUNCHER_METHOD_HTTP: &str = "http"; const ASPECT_LAUNCHER_METHOD_GITHUB: &str = "github"; const ASPECT_LAUNCHER_METHOD_LOCAL: &str = "local"; async fn _download_into_cache( client: &Client, cache_entry: &PathBuf, req: Request, download_msg: &str, ) -> Result<()> { // Stream to a tempfile let tmp_file = cache_entry.with_extension("tmp"); let tmpf = File::create(&tmp_file) .into_diagnostic() .context("failed to create temporary file")?; let metadata = fs::metadata(&tmp_file).into_diagnostic()?; let mut permissions = metadata.permissions(); let new_mode = 0o755; permissions.set_mode(new_mode); fs::set_permissions(&tmp_file, permissions).into_diagnostic()?; let mut tmp_writer = tokio::fs::File::from(tmpf); let response = client .execute(req) .await .into_diagnostic()? .error_for_status() .into_diagnostic()?; eprintln!("{}", download_msg); let total_size = response.content_length(); let mut byte_stream = response.bytes_stream(); let mut downloaded: u64 = 0; while let Some(item) = byte_stream .try_next() .await .into_diagnostic() .wrap_err("failed to stream content")? { let chunk_size = item.len() as u64; tokio::io::copy(&mut item.as_ref(), &mut tmp_writer) .await .into_diagnostic() .wrap_err("failed to slab stream to file")?; downloaded += chunk_size; if let Some(total) = total_size { let percent = ((downloaded as f64 / total as f64) * 100.0) as u64; eprint!( "\r{:.0} / {:.0} KB ({}%)", downloaded as f64 / 1024.0, total as f64 / 1024.0, percent ); io::stderr().flush().into_diagnostic()?; } else { eprint!("\r{:.0} KB", downloaded as f64 / 1024.0); io::stderr().flush().into_diagnostic()?; } } eprintln!(); // And move it into the cache tokio::fs::rename(&tmp_file, &cache_entry) .await .into_diagnostic() .context("failed to move tool")?; // FIXME: Check download integrity/signatures? Ok(()) } #[derive(Deserialize, Debug)] struct Release { assets: Vec<ReleaseArtifact>, } #[derive(Deserialize, Debug)] struct ReleaseArtifact { url: String, name: String, } fn headermap_from_hashmap<'a, I, S>(headers: I) -> HeaderMap where I: Iterator<Item = (S, S)> + 'a, S: AsRef<str> + 'a, { headers .map(|(name, val)| { ( HeaderName::from_str(name.as_ref()), HeaderValue::from_str(val.as_ref()), ) }) // We ignore the errors here. If you want to get a list of failed conversions, you can use Iterator::partition // to help you out here .filter(|(k, v)| k.is_ok() && v.is_ok()) .map(|(k, v)| (k.unwrap(), v.unwrap())) .collect() } fn gh_request(client: &Client, url: String) -> RequestBuilder { let mut headers = HeaderMap::new(); headers.insert( HeaderName::from_static("user-agent"), HeaderValue::from_static("aspect-launcher v0.0.1"), ); headers.insert( HeaderName::from_static("x-github-api-version"), HeaderValue::from_static("2022-11-28"), ); let mut builder = client.request(Method::GET, url).headers(headers); if let Ok(val) = env::var("GITHUB_TOKEN") && !val.is_empty() { builder = builder.bearer_auth(&val); } builder } async fn configure_tool_task( cache: AspectCache, root_dir: PathBuf, tool: Box<dyn ToolSpec + Send>, ) -> JoinHandle<Result<(PathBuf, String, HashMap<String, String>)>> { task::spawn((async move |cache: AspectCache, root_dir: PathBuf, tool: Box<dyn ToolSpec + Send>| -> Result<( PathBuf, String, HashMap<String, String>, )> { let mut errs: Vec<Result<()>> = Vec::new(); let client = reqwest::Client::new(); let liquid_globals = liquid::object!({ "version": tool.version(), // Per @platforms, sigh "bzlos": BZLOS.to_string(), "bzlarch": BZLARCH.to_string(), // Per golang "goos": GOOS.to_string(), "goarch": GOARCH.to_string(), "llvm_triple": LLVM_TRIPLE.to_string(), }); let liquid_parser = liquid::ParserBuilder::new().build().into_diagnostic()?; for source in tool.sources() { match source { ToolSource::Http { url, headers } => { let url = liquid_parser .parse(&url) .into_diagnostic()? .render(&liquid_globals) .into_diagnostic()?; let req_headers = headermap_from_hashmap(headers.iter()); let req = client .request(Method::GET, &url) .headers(req_headers) .build() .into_diagnostic()?; let tool_dest_file = cache.tool_path(&tool.name(), &url); let mut extra_envs = HashMap::new(); extra_envs.insert("ASPECT_LAUNCHER_ASPECT_CLI_URL".to_string(), url.clone()); if tool_dest_file.exists() { if debug_mode() { eprintln!( "{:} source {:?} found in cache {:?}", tool.name(), source, url ); }; return Ok(( tool_dest_file, ASPECT_LAUNCHER_METHOD_HTTP.to_string(), extra_envs, )); } fs::create_dir_all(tool_dest_file.parent().unwrap()).into_diagnostic()?; if debug_mode() { eprintln!( "{:} source {:?} downloading {:?} to {:?}", tool.name(), source, url, tool_dest_file ); }; let download_msg = format!("downloading aspect cli from {}", url); if let err @ Err(_) = _download_into_cache(&client, &tool_dest_file, req, &download_msg).await { errs.push(err); continue; }; return Ok(( tool_dest_file, ASPECT_LAUNCHER_METHOD_HTTP.to_string(), extra_envs, )); } ToolSource::GitHub { org, repo, release, artifact, } => { let release = liquid_parser .parse(&release) .into_diagnostic()? .render(&liquid_globals) .into_diagnostic()?; let artifact = liquid_parser .parse(&artifact) .into_diagnostic()? .render(&liquid_globals) .into_diagnostic()?; let url = format!( "https://api.github.com/repos/{org}/{repo}/releases/tags/{release}" ); let tool_dest_file = cache.tool_path(&tool.name(), &url); let mut extra_envs = HashMap::new(); extra_envs.insert("ASPECT_LAUNCHER_ASPECT_CLI_ORG".to_string(), org.clone()); extra_envs.insert("ASPECT_LAUNCHER_ASPECT_CLI_REPO".to_string(), repo.clone()); extra_envs.insert( "ASPECT_LAUNCHER_ASPECT_CLI_RELEASE".to_string(), release.clone(), ); extra_envs.insert( "ASPECT_LAUNCHER_ASPECT_CLI_ARTIFACT".to_string(), artifact.clone(), ); if tool_dest_file.exists() { if debug_mode() { eprintln!( "{:} source {:?} found in cache {:?}", tool.name(), source, &url ); }; return Ok(( tool_dest_file, ASPECT_LAUNCHER_METHOD_GITHUB.to_string(), extra_envs, )); } fs::create_dir_all(tool_dest_file.parent().unwrap()).into_diagnostic()?; let req = gh_request(&client, url) .header( HeaderName::from_static("accept"), HeaderValue::from_static("application/vnd.github+json"), ) .build() .into_diagnostic()?; let resp = client .execute(req.try_clone().unwrap()) .await .into_diagnostic()?; let release_data: Release = resp.json::<Release>().await.into_diagnostic()?; for asset in release_data.assets { if asset.name == *artifact { if debug_mode() { eprintln!( "{:} source {:?} downloading {:?} to {:?}", tool.name(), source, asset.url, tool_dest_file ); }; let req = gh_request(&client, asset.url) .header( HeaderName::from_static("accept"), HeaderValue::from_static("application/octet-stream"), ) .build() .into_diagnostic()?; let download_msg = format!( "downloading aspect cli version {} file {}", release, artifact ); if let err @ Err(_) = _download_into_cache(&client, &tool_dest_file, req, &download_msg) .await { errs.push(err); break; } return Ok(( tool_dest_file, ASPECT_LAUNCHER_METHOD_GITHUB.to_string(), extra_envs, )); } } errs.push(Err(miette!("unable to find a release artifact in github!"))); continue; } ToolSource::Local { path } => { let tool_dest_file = cache.tool_path(&tool.name(), path); // Don't pull local sources from the cache since the local development flow will // always be to copy the latest fs::create_dir_all(tool_dest_file.parent().unwrap()).into_diagnostic()?; let full_path = root_dir.join(path); if fs::exists(&full_path).into_diagnostic()? { if fs::exists(&tool_dest_file).into_diagnostic()? { tokio::fs::remove_file(&tool_dest_file) .await .into_diagnostic()?; } // We use copies because Bazel nukes the output tree on build errors and we want to resist that tokio::fs::copy(&full_path, &tool_dest_file) .await .into_diagnostic()?; if debug_mode() { eprintln!( "{:} source {:?} copying from {:?} to {:?}", tool.name(), source, full_path, tool_dest_file ); }; let metadata = fs::metadata(&tool_dest_file).into_diagnostic()?; let mut permissions = metadata.permissions(); let new_mode = 0o755; permissions.set_mode(new_mode); fs::set_permissions(&tool_dest_file, permissions).into_diagnostic()?; let mut extra_envs = HashMap::new(); extra_envs .insert("ASPECT_LAUNCHER_ASPECT_CLI_PATH".to_string(), path.clone()); return Ok(( tool_dest_file, ASPECT_LAUNCHER_METHOD_LOCAL.to_string(), extra_envs, )); } } } } Err(miette!(format!( "exhausted tool sources {:?}; errors occurred {:?}", tool.sources(), errs ))) })(cache.clone(), root_dir.clone(), tool)) } fn main() -> Result<ExitCode> { let cmd = Command::new("aspect") .disable_help_flag(true) .arg( Arg::new("version") .short('v') .long("version") .action(clap::ArgAction::SetTrue), ) .arg( arg!(<args> ...) .trailing_var_arg(true) .required(false) .allow_hyphen_values(true), ); let matches = cmd.get_matches(); if matches.get_flag("version") { let v = cargo_pkg_short_version(); println!("aspect launcher {v:}"); return Ok(ExitCode::SUCCESS); } // Fork the launcher and report usage match fork().unwrap() { Fork::Child => { // Honor DO_NOT_TRACK if do_not_track() { return Ok(ExitCode::SUCCESS); } // Report telemetry let threaded_rt = runtime::Runtime::new().into_diagnostic()?; threaded_rt.block_on(async { let _ = send_telemetry().await; }); Ok(ExitCode::SUCCESS) } Fork::Parent(_) => { // Deal with the config bits let (root_dir, config) = autoconf()?; let cache: AspectCache = AspectCache::default()?; let threaded_rt = runtime::Runtime::new().into_diagnostic()?; threaded_rt.block_on(async { let cli_task = configure_tool_task( cache.clone(), root_dir.clone(), Box::new(config.aspect_cli.clone()), ) .await; // Wait for fetches let cli = &config.aspect_cli; if debug_mode() { eprintln!("attempting to provision {cli:?}"); }; let (cli_path, method, extra_envs) = cli_task.await.into_diagnostic()??; if debug_mode() { eprintln!("provisioned at {cli_path:?}"); }; if debug_mode() { eprintln!("attempting to run {cli_path:?}"); }; // Punt let mut cmd = UnixCommand::new(&cli_path); cmd.env("ASPECT_LAUNCHER", "true"); cmd.env("ASPECT_LAUNCHER_VERSION", cargo_pkg_short_version()); cmd.env("ASPECT_LAUNCHER_ASPECT_CLI_METHOD", method); for (k, v) in extra_envs { cmd.env(k, v); } if let Some(args) = matches.get_many::<String>("args") { cmd.args(args); }; let err = cmd.exec(); Err::<(), _>(miette!(format!( "failed to punt to the `aspect-cli`, {:?}", err ))) })?; Ok(ExitCode::SUCCESS) } } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/aspect-launcher/src/cache.rs
crates/aspect-launcher/src/cache.rs
use std::fs; use std::path::PathBuf; use dirs::cache_dir; use miette::{miette, Context, IntoDiagnostic, Result}; use sha2::{Digest, Sha256}; #[derive(Debug, Clone)] pub struct AspectCache { root: PathBuf, } impl AspectCache { pub fn from(root: PathBuf) -> AspectCache { AspectCache { root: root.clone() } } pub fn default() -> Result<AspectCache> { let Some(data_dir) = cache_dir() else { return Err(miette!("unable to identify the user's cache directory")); }; let aspect_data_dir = data_dir.join(PathBuf::from("aspect/launcher")); fs::create_dir_all(&aspect_data_dir) .into_diagnostic() .wrap_err("unable to create `aspect` cache dir")?; Ok(AspectCache::from(aspect_data_dir)) } pub fn tool_path(&self, tool_name: &String, tool_source: &String) -> PathBuf { let mut hasher = Sha256::new(); hasher.update(tool_name.as_bytes()); hasher.update(tool_source.as_bytes()); let hash = format!("{:x}", hasher.finalize()); self.root.join(format!("bin/{0}/{1}/{0}", tool_name, hash)) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-proto/build.rs
crates/axl-proto/build.rs
use std::{env, fs, path::PathBuf}; use prost::Message; use prost_build::Config; use prost_types::{DescriptorProto, EnumDescriptorProto, FileDescriptorSet}; use tonic_prost_build::configure; fn main() -> Result<(), std::io::Error> { let descriptor_path = PathBuf::from(std::env::var("DESCRIPTOR").unwrap_or("descriptor.bin".into())); let fds = FileDescriptorSet::decode(std::fs::read(descriptor_path).unwrap().as_slice())?; let mut config = Config::new(); let return_expr = "::starlark::values::none::NoneOr::from_option(this.id.as_ref().map(|id| id.id.clone().unwrap()))"; let return_type = "::starlark::values::none::NoneOr<build_event_id::Id>"; config.field_attribute( "build_event_stream.BuildEvent.id", format!( r#"#[starbuf(return_expr="{}", return_type="{}")]"#, return_expr, return_type, ), ); let return_expr = "this.id.as_ref().map(|id| id.id.clone().unwrap()).unwrap().as_str_name()"; let return_type = "&'static str"; config.field_attribute( "build_event_stream.BuildEvent.last_message", format!( r#"#[starbuf(rename="kind", return_expr="{}", return_type="{}")]"#, return_expr, return_type, ), ); config.enable_type_names(); fn traverse( prefix: &str, config: &mut Config, enums: &Vec<EnumDescriptorProto>, desc: &Vec<DescriptorProto>, ) { for en in enums { config.type_attribute( format!("{}.{}", prefix, en.name()), r#"#[derive( ::starbuf_derive::Enumeration, ::allocative::Allocative, )]"#, ); } for desc in desc { for field in &desc.field { let path = format!("{}.{}.{}", prefix, desc.name(), field.name()); if field.type_name() == ".google.protobuf.Duration" { config.field_attribute( &path, format!(r#"#[starbuf(path = "{}", duration)]"#, path), ); config.field_attribute(&path, r#"#[allocative(skip)]"#); } else if field.type_name() == ".google.protobuf.Timestamp" { config.field_attribute( &path, format!(r#"#[starbuf(path = "{}", timestamp)]"#, path), ); config.field_attribute(&path, r#"#[allocative(skip)]"#); } else if field.type_name() == ".google.protobuf.Any" { config.field_attribute(&path, format!(r#"#[starbuf(path = "{}", any)]"#, path)); config.field_attribute(&path, r#"#[allocative(skip)]"#); } else { config.field_attribute(&path, format!(r#"#[starbuf(path = "{}")]"#, path)); } } config.type_attribute( format!("{}.{}", prefix, desc.name()), format!( r#" #[derive( ::starlark::values::ProvidesStaticType, ::derive_more::Display, ::starlark::values::Trace, ::starlark::values::NoSerialize, ::allocative::Allocative, ::starbuf_derive::Message )] #[display("{}")] "#, desc.name() ), ); for oneof in &desc.oneof_decl { let path = format!("{}.{}.{}", prefix, desc.name(), oneof.name()); config.field_attribute(&path, format!(r#"#[starbuf(path = "{}")]"#, path)); config.type_attribute( &path, "#[derive(::starbuf_derive::Oneof, ::allocative::Allocative)]", ); } traverse( format!("{}.{}", prefix, desc.name()).as_str(), config, &desc.enum_type, &desc.nested_type, ); } } for file in &fds.file { if file.package() == "google.devtools.build.v1" { continue; } traverse( file.package(), &mut config, &file.enum_type, &file.message_type, ); } configure() .build_client(true) .build_server(false) .compile_fds_with_config(fds, config)?; let out_dir = env::var("OUT_DIR").unwrap(); let build_event_stream = fs::read_to_string(format!("{out_dir}/build_event_stream.rs"))?; fs::write( format!("{out_dir}/build_event_stream.rs"), format!( r#"/// @Generated by build.rs #[starbuf_derive::types] pub mod build_event_stream {{ {build_event_stream} }} "# ), )?; let query = fs::read_to_string(format!("{out_dir}/blaze_query.rs"))?; fs::write( format!("{out_dir}/blaze_query.rs"), format!( r#" /// @Generated by build.rs #[starbuf_derive::types] pub mod blaze_query {{ {query} }} "# ), )?; let tools = fs::read_to_string(format!("{out_dir}/tools.protos.rs"))?; fs::write( format!("{out_dir}/tools.protos.rs"), format!( r#" /// @Generated by build.rs #[starbuf_derive::types] pub mod tools {{ pub mod protos {{ {tools} }} }} "# ), )?; let workspace_log = fs::read_to_string(format!("{out_dir}/workspace_log.rs"))?; fs::write( format!("{out_dir}/workspace_log.rs"), format!( r#" /// @Generated by build.rs #[starbuf_derive::types] pub mod workspace_log {{ {workspace_log} }} "# ), )?; Ok(()) }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-proto/src/lib.rs
crates/axl-proto/src/lib.rs
#![allow(clippy::all)] #![allow(deprecated)] // starbuf-derive skips deprecated fiels by default // however, deprecated fields still need to be used // to initialize structs, and that causes rust to issue // warnings; // See: https://github.com/rust-lang/rust/issues/47219 pub use prost_types::Any; pub use prost_types::Duration; pub use prost_types::Timestamp; include!(concat!(env!("OUT_DIR"), "/workspace_log.rs")); include!(concat!(env!("OUT_DIR"), "/build_event_stream.rs")); include!(concat!(env!("OUT_DIR"), "/blaze_query.rs")); include!(concat!(env!("OUT_DIR"), "/tools.protos.rs")); #[path = "./pb_impl.rs"] mod pb_impl; pub mod google { pub mod devtools { pub mod build { pub mod v1 { include!(concat!(env!("OUT_DIR"), "/google.devtools.build.v1.rs")); } } } } pub mod analysis { include!(concat!(env!("OUT_DIR"), "/analysis.rs")); } pub mod bazel_flags { include!(concat!(env!("OUT_DIR"), "/bazel_flags.rs")); } pub mod blaze { include!(concat!(env!("OUT_DIR"), "/blaze.rs")); pub mod invocation_policy { include!(concat!(env!("OUT_DIR"), "/blaze.invocation_policy.rs")); } pub mod strategy_policy { include!(concat!(env!("OUT_DIR"), "/blaze.strategy_policy.rs")); } } pub mod command_line { include!(concat!(env!("OUT_DIR"), "/command_line.rs")); } pub mod devtools { pub mod build { pub mod lib { pub mod packages { pub mod metrics { include!(concat!( env!("OUT_DIR"), "/devtools.build.lib.packages.metrics.rs" )); } } } } } pub mod failure_details { include!(concat!(env!("OUT_DIR"), "/failure_details.rs")); } pub mod options { include!(concat!(env!("OUT_DIR"), "/options.rs")); } pub mod stardoc_output { include!(concat!(env!("OUT_DIR"), "/stardoc_output.rs")); }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-proto/src/pb_impl.rs
crates/axl-proto/src/pb_impl.rs
impl super::build_event_stream::build_event_id::Id { pub fn as_str_name(&self) -> &'static str { match self { Self::Unknown(_) => "unknown", Self::Progress(_) => "progress", Self::Started(_) => "build_started", Self::BuildFinished(_) => "build_finished", Self::UnstructuredCommandLine(_) => "unstructured_command_line", Self::StructuredCommandLine(_) => "structured_command_line", Self::WorkspaceStatus(_) => "workspace_status", Self::OptionsParsed(_) => "options_parsed", Self::Fetch(_) => "fetch", Self::Configuration(_) => "configuration", Self::TargetConfigured(_) => "target_configured", Self::Pattern(_) => "pattern_expanded", Self::PatternSkipped(_) => "pattern_skipped", Self::NamedSet(_) => "named_set_of_files", Self::TargetCompleted(_) => "target_completed", Self::ActionCompleted(_) => "action_completed", Self::UnconfiguredLabel(_) => "unconfigured_label", Self::ConfiguredLabel(_) => "configured_label", Self::TestResult(_) => "test_result", Self::TestProgress(_) => "test_progress", Self::TestSummary(_) => "test_summary", Self::TargetSummary(_) => "target_summary", Self::BuildToolLogs(_) => "build_tool_logs", Self::BuildMetrics(_) => "build_metrics", Self::Workspace(_) => "workspace_config", Self::BuildMetadata(_) => "build_metadata", Self::ConvenienceSymlinksIdentified(_) => "convenience_symlinks_identified", Self::ExecRequest(_) => "exec_request", } } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/build-event-stream/src/lib.rs
crates/build-event-stream/src/lib.rs
mod auth; pub mod build_tool; pub mod client; pub mod lifecycle; mod stream_id;
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/build-event-stream/src/stream_id.rs
crates/build-event-stream/src/stream_id.rs
use axl_proto::google::devtools::build::v1::{ build_event::Event, stream_id::BuildComponent, StreamId, }; pub fn stream_id(build_id: String, invocation_id: String, ev: &Event) -> StreamId { StreamId { build_id, invocation_id, component: match ev { Event::InvocationAttemptStarted(_) | Event::InvocationAttemptFinished(_) => { BuildComponent::Controller } Event::BuildEnqueued(_) | Event::BuildFinished(_) => BuildComponent::Controller, Event::ComponentStreamFinished(_) | Event::BazelEvent(_) => BuildComponent::Tool, // These are not handled by Bazel. Event::ConsoleOutput(_) => todo!(), Event::BuildExecutionEvent(_) => todo!(), Event::SourceFetchEvent(_) => todo!(), } as i32, } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/build-event-stream/src/lifecycle.rs
crates/build-event-stream/src/lifecycle.rs
use std::time::SystemTime; use axl_proto::google::devtools::build::v1::{ build_event::{ BuildEnqueued, BuildFinished, Event, InvocationAttemptFinished, InvocationAttemptStarted, }, publish_lifecycle_event_request::ServiceLevel, BuildEvent, BuildStatus, OrderedBuildEvent, PublishLifecycleEventRequest, }; use prost_types::Timestamp; use super::stream_id::stream_id; pub fn lifecycle_request( build_id: String, invocation_id: String, sequence_number: i64, ev: Event, ) -> PublishLifecycleEventRequest { let now = SystemTime::now(); let stream_id = stream_id(build_id.clone(), invocation_id.clone(), &ev); PublishLifecycleEventRequest { service_level: ServiceLevel::Interactive as i32, build_event: Some(OrderedBuildEvent { sequence_number, stream_id: Some(stream_id), event: Some(BuildEvent { event: Some(ev), event_time: Some(Timestamp::from(now)), }), }), stream_timeout: None, notification_keywords: vec![], project_id: String::new(), check_preceding_lifecycle_events_present: false, } } // https://github.com/bazelbuild/bazel/blob/198c4c8aae1b5ef3d202f602932a99ce19707fc4/src/main/java/com/google/devtools/build/lib/buildeventservice/client/BuildEventServiceProtoUtil.java#L73 pub fn build_enqueued(build_id: String, invocation_id: String) -> PublishLifecycleEventRequest { lifecycle_request( build_id, invocation_id, 1, Event::BuildEnqueued(BuildEnqueued::default()), ) } // https://github.com/bazelbuild/bazel/blob/198c4c8aae1b5ef3d202f602932a99ce19707fc4/src/main/java/com/google/devtools/build/lib/buildeventservice/client/BuildEventServiceProtoUtil.java#L84 pub fn build_finished(build_id: String, invocation_id: String) -> PublishLifecycleEventRequest { lifecycle_request( build_id, invocation_id, 2, Event::BuildFinished(BuildFinished::default()), ) } //https://github.com/bazelbuild/bazel/blob/198c4c8aae1b5ef3d202f602932a99ce19707fc4/src/main/java/com/google/devtools/build/lib/buildeventservice/client/BuildEventServiceProtoUtil.java#L95 pub fn invocation_started(build_id: String, invocation_id: String) -> PublishLifecycleEventRequest { lifecycle_request( build_id, invocation_id, 2, Event::InvocationAttemptStarted(InvocationAttemptStarted::default()), ) } //https://github.com/bazelbuild/bazel/blob/198c4c8aae1b5ef3d202f602932a99ce19707fc4/src/main/java/com/google/devtools/build/lib/buildeventservice/client/BuildEventServiceProtoUtil.java#L108 pub fn invocation_finished( build_id: String, invocation_id: String, build_status: BuildStatus, ) -> PublishLifecycleEventRequest { lifecycle_request( build_id, invocation_id, 2, Event::InvocationAttemptFinished(InvocationAttemptFinished { details: None, invocation_status: Some(build_status), }), ) }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/build-event-stream/src/client.rs
crates/build-event-stream/src/client.rs
use std::collections::HashMap; use axl_proto::google::devtools::build::v1::{ publish_build_event_client::PublishBuildEventClient, PublishBuildToolEventStreamRequest, PublishBuildToolEventStreamResponse, PublishLifecycleEventRequest, }; use futures::Stream; use http::uri::InvalidUri; use tonic::{ service::interceptor::InterceptedService, transport::{Channel, ClientTlsConfig}, Request, Response, Streaming, }; use crate::auth::AuthInterceptor; pub struct Client { inner: PublishBuildEventClient<InterceptedService<Channel, AuthInterceptor>>, } #[derive(thiserror::Error, Debug)] pub enum ClientError { #[error(transparent)] InvalidEndpoint(#[from] InvalidUri), #[error(transparent)] Transport(#[from] tonic::transport::Error), #[error(transparent)] Status(#[from] tonic::Status), } impl Client { pub async fn new( endpoint: String, headers: HashMap<String, String>, ) -> Result<Self, ClientError> { let channel = Channel::from_shared(endpoint)? .user_agent("AXL")? .tls_config( ClientTlsConfig::new() .with_native_roots() .with_enabled_roots(), )? .connect_lazy(); let interceptor = AuthInterceptor::new(headers); let inner = PublishBuildEventClient::with_interceptor(channel, interceptor); Ok(Self { inner }) } pub async fn publish_lifecycle_event( &mut self, event: PublishLifecycleEventRequest, ) -> Result<Response<()>, ClientError> { let ev = self .inner .publish_lifecycle_event(Request::new(event)) .await?; Ok(ev) } pub async fn publish_build_tool_event_stream< S: Stream<Item = PublishBuildToolEventStreamRequest> + Send + 'static, >( &mut self, events: S, ) -> Result<Response<Streaming<PublishBuildToolEventStreamResponse>>, ClientError> { let x = self .inner .publish_build_tool_event_stream(Request::new(events)) .await?; Ok(x) } } #[cfg(test)] mod tests { use std::time::SystemTime; use axl_proto::{ build_event_stream::{ build_event::Payload, build_event_id::{ BuildFinishedId, BuildMetadataId, BuildStartedId, Id, OptionsParsedId, ProgressId, StructuredCommandLineId, UnstructuredCommandLineId, WorkspaceConfigId, }, build_finished::ExitCode, BuildEvent, BuildEventId, BuildFinished, BuildMetadata, BuildStarted, OptionsParsed, Progress, UnstructuredCommandLine, WorkspaceConfig, }, command_line::{ command_line_section::SectionType, ChunkList, CommandLine, CommandLineSection, Option as BazelOption, OptionList, }, google::devtools::build::v1::BuildStatus, }; use prost_types::Timestamp; use tokio_stream::{self, StreamExt}; use crate::{build_tool, lifecycle}; use super::*; #[tokio::test] async fn connect_test() -> Result<(), ClientError> { let mut client = Client::new( "https://testing.io".to_string(), HashMap::from_iter(vec![( "x-api-key".to_string(), "your_key_goes_here".to_string(), )]), ) .await?; let uuid = uuid::Uuid::new_v4().to_string(); let build_id = uuid.to_string(); let invocation_id = uuid.to_string(); // https://github.com/bazelbuild/bazel/blob/198c4c8aae1b5ef3d202f602932a99ce19707fc4/src/main/java/com/google/devtools/build/lib/buildeventservice/BuildEventServiceUploader.java#L322-L341 let result = client .publish_lifecycle_event(lifecycle::build_enqueued( build_id.to_string(), invocation_id.to_string(), )) .await?; eprintln!("{:?}", result); let result = client .publish_lifecycle_event(lifecycle::invocation_started( build_id.to_string(), invocation_id.to_string(), )) .await?; eprintln!("{:?}", result); let mut stream = client .publish_build_tool_event_stream(tokio_stream::iter(vec![ build_tool::bazel_event( build_id.to_string(), invocation_id.to_string(), 1, &BuildEvent { id: Some(BuildEventId { id: Some(Id::Started(BuildStartedId {})), }), children: vec![], last_message: false, payload: Some(Payload::Started(BuildStarted { build_tool_version: "8.0.0".to_string(), command: "build".to_string(), options_description: "".to_string(), server_pid: 1246, start_time: Some(Timestamp::from(SystemTime::now())), uuid: uuid.to_string(), working_directory: "/tmp/work".to_string(), workspace_directory: "/tmp/work".to_string(), ..Default::default() })), }, ), build_tool::bazel_event( build_id.to_string(), invocation_id.to_string(), 2, &BuildEvent { id: Some(BuildEventId { id: Some(Id::BuildMetadata(BuildMetadataId {})), }), children: vec![], last_message: false, payload: Some(Payload::BuildMetadata(BuildMetadata { metadata: HashMap::new(), })), }, ), build_tool::bazel_event( build_id.to_string(), invocation_id.to_string(), 3, &BuildEvent { id: Some(BuildEventId { id: Some(Id::UnstructuredCommandLine(UnstructuredCommandLineId {})), }), children: vec![], last_message: false, payload: Some(Payload::UnstructuredCommandLine( UnstructuredCommandLine::default(), )), }, ), build_tool::bazel_event( build_id.to_string(), invocation_id.to_string(), 4, &BuildEvent { id: Some(BuildEventId { id: Some(Id::OptionsParsed(OptionsParsedId {})), }), children: vec![], last_message: false, payload: Some(Payload::OptionsParsed(OptionsParsed { startup_options: vec![], explicit_startup_options: vec![], cmd_line: vec![ "--nobuild_runfile_links".to_string(), "--enable_platform_specific_config".to_string(), "--noexperimental_check_external_repository_files".to_string(), "--experimental_fetch_all_coverage_outputs".to_string(), "--heap_dump_on_oom".to_string(), ], ..Default::default() })), }, ), build_tool::bazel_event( build_id.to_string(), invocation_id.to_string(), 5, &BuildEvent { id: Some(BuildEventId { id: Some(Id::StructuredCommandLine(StructuredCommandLineId { command_line_label: "build".to_string(), })), }), children: vec![], last_message: false, payload: Some(Payload::StructuredCommandLine(CommandLine { command_line_label: "original".to_string(), sections: vec![ CommandLineSection { section_label: "executable".to_string(), section_type: Some(SectionType::ChunkList(ChunkList { chunk: vec!["bazel".to_string()], })), }, CommandLineSection { section_label: "startup options".to_string(), section_type: Some(SectionType::OptionList(OptionList { option: vec![], })), }, CommandLineSection { section_label: "command".to_string(), section_type: Some(SectionType::ChunkList(ChunkList { chunk: vec!["build".to_string()], })), }, CommandLineSection { section_label: "command options".to_string(), section_type: Some(SectionType::OptionList(OptionList { option: vec![BazelOption { combined_form: "--foo=test".to_string(), effect_tags: vec![], metadata_tags: vec![], option_name: "foo".to_string(), option_value: "test".to_string(), source: ".bazelrc".to_string(), }], })), }, CommandLineSection { section_label: "residual".to_string(), section_type: Some(SectionType::ChunkList(ChunkList { chunk: vec!["...".to_string(), "REDACTED".to_string()], })), }, ], })), }, ), build_tool::bazel_event( build_id.to_string(), invocation_id.to_string(), 6, &BuildEvent { id: Some(BuildEventId { id: Some(Id::Workspace(WorkspaceConfigId {})), }), children: vec![], last_message: false, payload: Some(Payload::WorkspaceInfo(WorkspaceConfig { local_exec_root: "/private/var/tmp/_bazel_thesayyn/417a0dd96fe4f36c47b911f3d33c4442/execroot/_main".to_string() })), }, ), build_tool::bazel_event( build_id.to_string(), invocation_id.to_string(), 7, &BuildEvent { id: Some(BuildEventId { id: Some(Id::Progress(ProgressId { opaque_count: 0 })), }), children: vec![], last_message: false, payload: Some(Payload::Progress(Progress { stdout: "This output came from somewhere else.".to_string(), stderr: "".to_string() })), }, ), build_tool::bazel_event( build_id.to_string(), invocation_id.to_string(), 8, &BuildEvent { id: Some(BuildEventId { id: Some(Id::Progress(ProgressId { opaque_count: 0 })), }), children: vec![], last_message: false, payload: Some(Payload::Progress(Progress { stdout: "Build succesful!".to_string(), stderr: "".to_string() })), }, ), build_tool::bazel_event( build_id.to_string(), invocation_id.to_string(), 9, &BuildEvent { id: Some(BuildEventId { id: Some(Id::BuildFinished(BuildFinishedId {})), }), children: vec![], last_message: true, payload: Some(Payload::Finished(BuildFinished { exit_code: Some(ExitCode { code: 0, name: "normal".to_string(), }), failure_detail: None, finish_time: Some(Timestamp::from(SystemTime::now())), ..Default::default() })), }, ), ])) .await? .into_inner(); eprintln!("sent succesfully {:?}", stream); while let Some(event) = stream.next().await { match event { Ok(ev) => println!("{ev:?}"), Err(err) => panic!("{}", err), } } let result = client .publish_lifecycle_event(lifecycle::invocation_finished( build_id.to_string(), invocation_id.to_string(), BuildStatus { result: 0, final_invocation_id: build_id.to_string(), build_tool_exit_code: Some(0), error_message: String::new(), details: None, }, )) .await?; eprintln!("{:?}", result); let result = client .publish_lifecycle_event(lifecycle::build_finished( build_id.to_string(), invocation_id.to_string(), )) .await?; eprintln!("{:?}", result); Ok(()) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/build-event-stream/src/auth.rs
crates/build-event-stream/src/auth.rs
use std::collections::HashMap; use std::str::FromStr; use tonic::metadata::{MetadataKey, MetadataValue}; use tonic::service::Interceptor; pub struct AuthInterceptor { headers: HashMap<String, String>, } impl AuthInterceptor { pub fn new(headers: HashMap<String, String>) -> Self { Self { headers } } } impl Interceptor for AuthInterceptor { fn call( &mut self, mut request: tonic::Request<()>, ) -> Result<tonic::Request<()>, tonic::Status> { // https://github.com/bazelbuild/bazel/blob/198c4c8aae1b5ef3d202f602932a99ce19707fc4/src/main/java/com/google/devtools/build/lib/buildeventservice/BazelBuildEventServiceModule.java#L165 for (k, v) in &self.headers { let val = MetadataValue::from_str(v.as_str()).unwrap(); let key = MetadataKey::from_str(k.as_str()).unwrap(); request.metadata_mut().append(key, val); } Ok(request) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/build-event-stream/src/build_tool.rs
crates/build-event-stream/src/build_tool.rs
use std::time::SystemTime; use axl_proto::{ build_event_stream::BuildEvent as BazelBuildEvent, google::devtools::build::v1::{ build_event::Event, BuildEvent, OrderedBuildEvent, PublishBuildToolEventStreamRequest, }, }; use prost_types::{Any, Timestamp}; use super::stream_id::stream_id; pub fn stream_request( build_id: String, invocation_id: String, seq: i64, event: BuildEvent, ) -> PublishBuildToolEventStreamRequest { PublishBuildToolEventStreamRequest { check_preceding_lifecycle_events_present: false, notification_keywords: vec![], ordered_build_event: Some(OrderedBuildEvent { sequence_number: seq, stream_id: Some(stream_id( build_id, invocation_id, event.event.as_ref().unwrap(), )), event: Some(event), }), project_id: String::new(), } } pub fn bazel_event( build_id: String, invocation_id: String, seq: i64, event: &BazelBuildEvent, ) -> PublishBuildToolEventStreamRequest { let packed = Any::from_msg(event).expect("failed to encode bazel event"); stream_request( build_id, invocation_id, seq, BuildEvent { event_time: Some(Timestamp::from(SystemTime::now())), event: Some(Event::BazelEvent(packed)), }, ) }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/aspect-cli/src/helpers.rs
crates/aspect-cli/src/helpers.rs
use std::path::PathBuf; use axl_runtime::module::{AXL_CONFIG_EXTENSION, AXL_MODULE_FILE, AXL_SCRIPT_EXTENSION}; use tokio::fs; use tracing::instrument; // Constants for special directory names used in module resolution. // These define the structure for local modules (e.g., .aspect/axl/module_name). pub const DOT_ASPECT_FOLDER: &str = ".aspect"; /// Asynchronously finds the root directory starting from the given `current_work_dir`. /// It traverses the ancestors of `current_work_dir` from deepest to shallowest. /// The root dir is identified as the first (deepest) ancestor directory of the current working /// directory that contains at least one of the following boundary files: MODULE.aspect, MODULE.bazel, /// MODULE.bazel.lock, REPO.bazel, WORKSPACE, or WORKSPACE.bazel. /// If such a directory is found, it returns Ok with the PathBuf of that directory. /// If no such directory is found, returns the `current_work_dir` #[instrument] pub async fn find_repo_root(current_work_dir: &PathBuf) -> Result<PathBuf, ()> { async fn err_if_exists(path: PathBuf) -> Result<(), ()> { match fs::try_exists(path).await { Ok(true) => Err(()), Ok(false) => Ok(()), Err(_) => Ok(()), } } for ancestor in current_work_dir.ancestors().into_iter() { let repo_root = tokio::try_join!( err_if_exists(ancestor.join(AXL_MODULE_FILE)), // Repository boundary marker files: https://bazel.build/external/overview#repository err_if_exists(ancestor.join("MODULE.bazel")), err_if_exists(ancestor.join("MODULE.bazel.lock")), err_if_exists(ancestor.join("REPO.bazel")), err_if_exists(ancestor.join("WORKSPACE")), err_if_exists(ancestor.join("WORKSPACE.bazel")), ); // No error means there was no match for any of the branches. if repo_root.is_ok() { continue; } else { return Ok(ancestor.to_path_buf()); } } return Ok(current_work_dir.clone()); } /// Returns a list of axl search paths by constructing paths from the `root_dir` up to the `current_dir`, /// appending ".aspect" to each path. If the relative path from `root_dir` to `current_dir` includes /// a ".aspect" component, the search stops at the parent directory of that ".aspect", excluding /// ".aspect" and any subdirectories from the results. #[instrument] pub fn get_default_axl_search_paths( current_work_dir: &PathBuf, root_dir: &PathBuf, ) -> Vec<PathBuf> { if let Ok(rel_path) = current_work_dir.strip_prefix(root_dir) { let mut paths = vec![root_dir.join(DOT_ASPECT_FOLDER)]; let mut current = root_dir.clone(); for component in rel_path.components() { if component.as_os_str() == DOT_ASPECT_FOLDER { break; } current = current.join(component); paths.push(current.join(DOT_ASPECT_FOLDER)); } paths } else { vec![] } } /// Asynchronously searches through the provided list of directories (`search_paths`) and collects /// all files that have the extension matching `axl`. /// For each directory, it checks if it exists and is a directory, then reads its entries and /// filters for files with the specified extension. /// Returns a vector of `PathBuf` for the found files, or an error if a file system operation fails. #[instrument] pub async fn search_sources( search_paths: &Vec<PathBuf>, ) -> Result<(Vec<PathBuf>, Vec<PathBuf>), std::io::Error> { let mut found: Vec<PathBuf> = vec![]; let mut configs: Vec<PathBuf> = vec![]; for dir in search_paths { let dir_metadata = fs::metadata(&dir).await; if dir_metadata.map_or_else(|_| false, |meta| meta.is_dir()) { let mut entries = fs::read_dir(&dir).await?; while let Ok(Some(entry)) = entries.next_entry().await { let path = entry.path(); if !path.is_file() { continue; } if path.ends_with(AXL_CONFIG_EXTENSION) { configs.push(path); } else if path .extension() .map_or(false, |e| e == AXL_SCRIPT_EXTENSION) { found.push(path); } } } } Ok((found, configs)) }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/aspect-cli/src/trace.rs
crates/aspect-cli/src/trace.rs
use opentelemetry::{global, trace::TracerProvider as _, KeyValue}; use opentelemetry_otlp::{tonic_types::transport::ClientTlsConfig, WithTonicConfig}; use opentelemetry_sdk::{ metrics::{MeterProviderBuilder, PeriodicReader, SdkMeterProvider}, trace::{RandomIdGenerator, Sampler, SdkTracerProvider}, Resource, }; use opentelemetry_semantic_conventions::{attribute::SERVICE_VERSION, SCHEMA_URL}; use tracing_core::Level; use tracing_opentelemetry::{MetricsLayer, OpenTelemetryLayer}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; // Create a Resource that captures information about the entity for which telemetry is recorded. fn resource() -> Resource { Resource::builder() .with_service_name("aspect-cli") .with_schema_url( [KeyValue::new( SERVICE_VERSION, aspect_telemetry::cargo_pkg_version(), )], SCHEMA_URL, ) .build() } // Construct MeterProvider for MetricsLayer fn init_meter_provider() -> SdkMeterProvider { let exporter = opentelemetry_otlp::MetricExporter::builder() .with_http() .with_temporality(opentelemetry_sdk::metrics::Temporality::default()) .build() .unwrap(); let reader = PeriodicReader::builder(exporter) .with_interval(std::time::Duration::from_secs(30)) .build(); let meter_provider = MeterProviderBuilder::default() .with_resource(resource()) .with_reader(reader) .build(); global::set_meter_provider(meter_provider.clone()); meter_provider } // Construct TracerProvider for OpenTelemetryLayer fn init_tracer_provider() -> SdkTracerProvider { let exporter = opentelemetry_otlp::SpanExporter::builder() .with_tonic() .with_tls_config(ClientTlsConfig::new().with_native_roots()) .build() .unwrap(); SdkTracerProvider::builder() // Customize sampling strategy .with_sampler(Sampler::ParentBased(Box::new(Sampler::TraceIdRatioBased( 1.0, )))) // If export trace to AWS X-Ray, you can use XrayIdGenerator .with_id_generator(RandomIdGenerator::default()) .with_resource(resource()) .with_batch_exporter(exporter) .build() } // Initialize tracing-subscriber and return OtelGuard for opentelemetry-related termination processing pub fn init() -> OtelGuard { let tracer_provider = init_tracer_provider(); let meter_provider = init_meter_provider(); let tracer = tracer_provider.tracer("tracing-otel-subscriber"); tracing_subscriber::registry() // The global level filter prevents the exporter network stack // from reentering the globally installed OpenTelemetryLayer with // its own spans while exporting, as the libraries should not use // tracing levels below DEBUG. If the OpenTelemetry layer needs to // trace spans and events with higher verbosity levels, consider using // per-layer filtering to target the telemetry layer specifically, // e.g. by target matching. .with(tracing_subscriber::filter::LevelFilter::from_level( Level::INFO, )) .with(MetricsLayer::new(meter_provider.clone())) .with(OpenTelemetryLayer::new(tracer)) .init(); OtelGuard { tracer_provider, meter_provider, } } pub(crate) struct OtelGuard { tracer_provider: SdkTracerProvider, meter_provider: SdkMeterProvider, } impl Drop for OtelGuard { fn drop(&mut self) { if let Err(err) = self.tracer_provider.shutdown() { eprintln!("{err:?}"); } if let Err(err) = self.meter_provider.shutdown() { eprintln!("{err:?}"); } } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/aspect-cli/src/flags.rs
crates/aspect-cli/src/flags.rs
use axl_runtime::engine::task_arg::TaskArg; use clap::{value_parser, Arg, ArgAction}; pub(crate) fn convert_arg(name: &String, arg: &TaskArg) -> Arg { match arg { TaskArg::String { required, default } => Arg::new(name) .long(name) .value_name(name) .required(required.to_owned()) .default_value(default.to_string()) .value_parser(value_parser!(String)), TaskArg::Boolean { required, default } => Arg::new(name) .long(name) .value_name(name) .required(required.to_owned()) .default_value(default.to_string()) .value_parser(value_parser!(bool)) .num_args(0..=1) .require_equals(true) .default_missing_value("true"), TaskArg::Int { required, default } => Arg::new(name) .long(name) .value_name(name) .required(required.to_owned()) .default_value(default.to_string()) .value_parser(value_parser!(i32)), TaskArg::UInt { required, default } => Arg::new(name) .long(name) .value_name(name) .required(required.to_owned()) .default_value(default.to_string()) .value_parser(value_parser!(u32)), TaskArg::Positional { minimum, maximum, default, } => { let mut it = Arg::new(name) .value_parser(value_parser!(String)) .value_name(name) .num_args(minimum.to_owned() as usize..=maximum.to_owned() as usize); if let Some(default) = default { it = it.default_values(default); } it } TaskArg::TrailingVarArgs => Arg::new(name) .value_parser(value_parser!(String)) .value_name(name) .allow_hyphen_values(true) .last(true) .num_args(0..), TaskArg::StringList { required, default } => { let mut it = Arg::new(name) .long(name) .value_name(name) .action(ArgAction::Append) .required(*required) .value_parser(value_parser!(String)); if !default.is_empty() { it = it.default_values(default.clone()); } it } TaskArg::BooleanList { required, default } => { let mut it = Arg::new(name) .long(name) .value_name(name) .action(ArgAction::Append) .required(*required) .value_parser(value_parser!(bool)) .num_args(0..=1) .default_missing_value("true"); if !default.is_empty() { let default: Vec<String> = default.iter().map(|&b| b.to_string()).collect(); it = it.default_values(default); } it } TaskArg::IntList { required, default } => { let mut it = Arg::new(name) .long(name) .value_name(name) .action(ArgAction::Append) .required(*required) .value_parser(value_parser!(i32)); if !default.is_empty() { let default: Vec<String> = default.iter().map(|&i| i.to_string()).collect(); it = it.default_values(default); } it } TaskArg::UIntList { required, default } => { let mut it = Arg::new(name) .long(name) .value_name(name) .action(ArgAction::Append) .required(*required) .value_parser(value_parser!(u32)); if !default.is_empty() { let default: Vec<String> = default.iter().map(|&u| u.to_string()).collect(); it = it.default_values(default); } it } } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/aspect-cli/src/cmd_tree.rs
crates/aspect-cli/src/cmd_tree.rs
use std::collections::HashMap; use axl_runtime::engine::task::{TaskLike, MAX_TASK_GROUPS}; use clap::{value_parser, Arg, ArgMatches, Command}; use thiserror::Error; const TASK_ID: &'static str = "@@@$'__AXL_TASK_ID__'$@@@"; // Clap's help generation sorts by (display_order, name)—-equal display_order values fall back to name-based sorting. const TASK_COMMAND_DISPLAY_ORDER: usize = 0; const TASK_GROUP_DISPLAY_ORDER: usize = 1; pub const BUILTIN_COMMAND_DISPLAY_ORDER: usize = 2; #[derive(Default)] pub struct CommandTree { // mapping of task subgroup to tree that contains subcommand. pub(crate) subgroups: HashMap<String, CommandTree>, // mapping of task name to the path that defines the task pub(crate) tasks: HashMap<String, Command>, } #[derive(Error, Debug)] pub enum TreeError { #[error( "task {0:?} in group {1:?} (defined in {2:?}) conflicts with a previously defined group" )] TaskGroupConflict(String, Vec<String>, String), #[error( "group {0:?} from task {1:?} in group {2:?} (defined in {3:?}) conflicts with a previously defined task" )] GroupConflictTask(String, String, Vec<String>, String), #[error( "task {0:?} in group {1:?} (defined in {2:?}) conflicts with a previously defined task" )] TaskConflict(String, Vec<String>, String), #[error("task {0:?} (defined in {1:?}) cannot have more than {2:?} group levels")] TooManyGroups(String, String, usize), #[error("task {0:?} in group {1:?} conflicts with a previously defined command")] TaskCommandConflict(String, Vec<String>), #[error("group {0:?} conflicts with a previously defined command")] GroupCommandConflict(Vec<String>), } impl CommandTree { pub fn insert( &mut self, name: &str, group: &[String], subgroup: &[String], path: &String, cmd: Command, ) -> Result<(), TreeError> { if group.len() > MAX_TASK_GROUPS { // This error is a defence-in-depth as the task evaluator should check for MAX_TASK_GROUPS return Err(TreeError::TooManyGroups( name.to_string(), path.clone(), MAX_TASK_GROUPS, )); } if subgroup.is_empty() { if self.subgroups.contains_key(name) { return Err(TreeError::TaskGroupConflict( name.to_string(), group.to_vec(), path.clone(), )); } if self.tasks.insert(name.to_string(), cmd).is_some() { return Err(TreeError::TaskConflict( name.to_string(), group.to_vec(), path.clone(), )); } } else { let first = &subgroup[0]; if self.tasks.contains_key(first) { return Err(TreeError::GroupConflictTask( first.clone(), name.to_string(), group.to_vec(), path.clone(), )); } let subtree = self.subgroups.entry(first.clone()).or_default(); subtree.insert(name, group, &subgroup[1..], path, cmd)?; } Ok(()) } pub fn as_command(&self, mut current: Command, group: &[String]) -> Result<Command, TreeError> { // Collect all subcommand names (groups and tasks) and sort them alphabetically for (name, subtree) in &self.subgroups { let mut group = group.to_vec(); group.push(name.clone()); if current.find_subcommand(name).is_some() { return Err(TreeError::GroupCommandConflict(group.to_vec())); } let mut subcmd = Command::new(name.clone()) // customize the subcommands section title to "Tasks:" .subcommand_help_heading("Tasks") // customize the usage string to use <TASK> .subcommand_value_name("TASK") .about(format!("\x1b[3m{}\x1b[0m task group", name)) .display_order(TASK_GROUP_DISPLAY_ORDER); subcmd = subtree.as_command(subcmd, &group)?; current = current.subcommand(subcmd); } for (name, subcmd) in &self.tasks { if current.find_subcommand(name).is_some() { return Err(TreeError::TaskCommandConflict( name.to_string(), group.to_vec(), )); } current = current.subcommand(subcmd); } // Require subcommand if are subgroups or tasks if !self.subgroups.is_empty() || !self.tasks.is_empty() { current = current.subcommand_required(true); } Ok(current) } pub fn get_task_id(&self, matches: &ArgMatches) -> usize { assert!(matches.contains_id(TASK_ID)); matches.get_one::<usize>(TASK_ID).unwrap().to_owned() } } pub fn make_command_from_task( name: &String, defined_in: &str, indice: String, task: &dyn TaskLike<'_>, ) -> Command { // Generate a default task description if none was provided by task let about = if task.description().is_empty() { format!( "\x1b[3m{}\x1b[0m task defined in \x1b[3m{}\x1b[0m", name, defined_in, ) } else { task.description().clone() }; let mut cmd = Command::new(name) .about(about) .display_order(TASK_COMMAND_DISPLAY_ORDER) .arg( Arg::new(TASK_ID) .long(TASK_ID) .hide(true) .hide_default_value(true) .hide_short_help(true) .hide_possible_values(true) .hide_long_help(true) .value_parser(value_parser!(usize)) .default_value(indice), ); for (name, arg) in task.args() { let arg = crate::flags::convert_arg(&name, arg); cmd = cmd.arg(arg); } cmd }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/aspect-cli/src/main.rs
crates/aspect-cli/src/main.rs
mod cmd_tree; mod flags; mod helpers; mod trace; use std::collections::HashMap; use std::env::var; use std::path::PathBuf; use std::process::ExitCode; use aspect_telemetry::{cargo_pkg_short_version, cargo_pkg_version, do_not_track, send_telemetry}; use axl_runtime::engine::config::TaskMut; use axl_runtime::engine::task_arg::TaskArg; use axl_runtime::engine::task_args::TaskArgs; use axl_runtime::eval::{self, task::TaskModuleLike, ModuleScope}; use axl_runtime::module::{AxlModuleEvaluator, DiskStore}; use axl_runtime::module::{AXL_MODULE_FILE, AXL_ROOT_MODULE_NAME}; use clap::{Arg, ArgAction, Command}; use miette::{miette, IntoDiagnostic}; use starlark::environment::Module; use starlark::values::ValueLike; use tokio::task; use tokio::task::spawn_blocking; use tracing::info_span; use crate::cmd_tree::{make_command_from_task, CommandTree, BUILTIN_COMMAND_DISPLAY_ORDER}; use crate::helpers::{find_repo_root, get_default_axl_search_paths, search_sources}; // Helper function to check if debug mode is enabled based on the ASPECT_DEBUG environment variable. fn debug_mode() -> bool { match var("ASPECT_DEBUG") { Ok(val) => !val.is_empty(), _ => false, } } // Must use a multi thread runtime with at least 3 threads for following reasons; // // Main thread (1) which drives the async runtime and all the other machinery shall // not be starved of cpu time to perform async tasks, its sole purpose is to // execute Rust code that drives the async runtime. // // Starlark thread (2) for command execution that is spawned via spawn_blocking will allow Starlark // code run on a blocking thread pool separate from the threads that drive the async work. // // On the other hand, all the other async tasks, including those spawned by Starlark // async machinery get to run on any of these worker threads (3+) until they are ready. // // As a special exception the build event machinery and build event sinks get // their own threads (3+) to react to IO streams in a timely manner. // // TODO: create a diagram of how all this ties together. #[tokio::main(flavor = "multi_thread", worker_threads = 3)] async fn main() -> miette::Result<ExitCode> { // Honor DO_NOT_TRACK if !do_not_track() { let _ = task::spawn(send_telemetry()); } // Initialize tracing for logging and instrumentation. let _tracing = trace::init(); // Enter the root tracing span for the entire application. let _root = info_span!("root").entered(); // Get the current working directory. let current_work_dir = std::env::current_dir().into_diagnostic()?; // Find the repository root directory asynchronously. let repo_root = find_repo_root(&current_work_dir) .await .map_err(|err| miette!("could not find root directory: {:?}", err))?; // Create a DiskStore for managing module storage on disk. let disk_store = DiskStore::new(repo_root.clone()); // Initialize the AxlModuleEvaluator for evaluating AXL modules. let module_eval = AxlModuleEvaluator::new(repo_root.clone()); // Enter a tracing span for expanding the module store. let _ = info_span!("expand_module_store").enter(); // Creates the module store and evaluates the root MODULE.aspect (if it exists) for axl_*_deps, use_task, etc... let root_module_store = module_eval .evaluate(AXL_ROOT_MODULE_NAME.to_string(), repo_root.clone()) .into_diagnostic()?; // Expand all module dependencies (including the builtin @aspect module) to the disk store and collect their root paths. // This results in a Vec of (String, PathBuf) such as // [ // ( "aspect", "/Users/username/Library/Caches/axl/deps/27e6d838c365a7c5d79674a7b6c7ec7b8d22f686dbcc8088a8d1454a6489a9ae/aspect" ), // ( "experimental", "/Users/username/Library/Caches/axl/deps/27e6d838c365a7c5d79674a7b6c7ec7b8d22f686dbcc8088a8d1454a6489a9ae/experimental" ), // ( "local", "/Users/username/Library/Caches/axl/deps/27e6d838c365a7c5d79674a7b6c7ec7b8d22f686dbcc8088a8d1454a6489a9ae/local" ), // ] let module_roots = disk_store .expand_store(&root_module_store) .await .into_diagnostic()?; // Collect root and dependency modules into a vector of modules with exported tasks. let mut modules = vec![( root_module_store.module_name, root_module_store.module_root, root_module_store.tasks.take(), )]; for (name, root) in module_roots { let module_store = module_eval.evaluate(name, root).into_diagnostic()?; if debug_mode() { eprintln!( "module @{} at {:?}", module_store.module_name, module_store.module_root ); }; modules.push(( module_store.module_name, module_store.module_root, module_store.tasks.take(), )) } // Scan for .axl scripts and .config.axl files in the default search paths // (based on current directory and repo root). let search_paths = get_default_axl_search_paths(&current_work_dir, &repo_root); let (scripts, configs) = search_sources(&search_paths).await.into_diagnostic()?; // Enter a tracing span for evaluation of scripts and configs. let espan = info_span!("eval"); // Starlark thread for command execution that is spawned via spawn_blocking will allow Starlark // code run on a blocking thread pool separate from the threads that drive the async work. let out = spawn_blocking(move || { let _enter = espan.enter(); let axl_deps_root = disk_store.deps_path(); let cli_version = cargo_pkg_short_version(); // Evaluate all scripts to find tasks and configs. The order of task discovery will be load bearing in the future // when task overloading is supported // 1. repository axl_sources // 2. use_task in the root module // 3. auto_use_tasks from the @aspect built-in module (if not overloaded by an dep in the root MODULE.aspect) // 4. auto_use_tasks from axl module deps in the root MODULE.aspect let axl_loader = eval::Loader::new(&cli_version, &repo_root, &axl_deps_root); // Create evaluators for tasks and configs. let task_eval = eval::task::TaskEvaluator::new(&axl_loader); let config_eval = eval::config::ConfigEvaluator::new(&axl_loader); // Evaluate auto-discovered AXL scripts to scan for tasks let task_modules: Vec<Module> = scripts .iter() .map(|path| { let rel_path = path.strip_prefix(&repo_root).unwrap().to_path_buf(); task_eval.eval( ModuleScope { name: AXL_ROOT_MODULE_NAME.to_string(), path: repo_root.clone(), }, &rel_path, ) }) .collect::<Result<Vec<_>, _>>() .into_diagnostic()?; // Evaluate AXL scripts from use_task statements in MODULE.aspect files. let mut use_task_modules: Vec<( String, PathBuf, HashMap<PathBuf, (Module, String, Vec<String>)>, )> = vec![]; for (module_name, module_root, map) in modules.into_iter() { let mut mmap = HashMap::new(); for (path, (label, symbols)) in map.into_iter() { let rel_path = path.strip_prefix(&module_root).unwrap().to_path_buf(); let module = task_eval .eval( ModuleScope { name: module_name.clone(), path: module_root.clone(), }, &rel_path, ) .into_diagnostic()?; mmap.insert(path, (module, label, symbols)); } use_task_modules.push((module_name, module_root, mmap)); } // Collect tasks from evaluated scripts. let mut tasks: Vec<TaskMut> = Vec::new(); for (i, module) in task_modules.iter().enumerate() { let path = scripts.get(i).unwrap(); for symbol in module.tasks() { let def = module .get_task(symbol) .expect("symbol should have been defined."); let name = if def.name().is_empty() { symbol.to_string() } else { def.name().clone() }; tasks.push(TaskMut::new( &module, symbol.to_string(), path.to_string_lossy().to_string(), name, def.group().clone(), )); } } for (module_name, module_root, map) in use_task_modules.iter() { for (path, (module, label, symbols)) in map.iter() { for symbol in symbols { if module.has_name(&symbol) { if !module.has_task(&symbol) { return Err(miette!( "invalid use_task({:?}, {:?}) call in @{} module at {}/{}", label, symbol, module_name, module_root.display(), AXL_MODULE_FILE )); }; let def = module .get_task(symbol.as_str()) .expect("symbol should have been defined."); let name = if def.name().is_empty() { symbol.as_str().to_string() } else { def.name().clone() }; tasks.push(TaskMut::new( &module, symbol.to_string(), path.to_string_lossy().to_string(), name, def.group().clone(), )); } else { return Err(miette!( "task symbol {:?} not found in @{} module use_task({:?}, {:?}) at {}/{}", symbol, module_name, label, symbol, module_root.display(), AXL_MODULE_FILE )); } } } } // Run all config functions, passing in vector of mutable tasks for configuration let config = config_eval .run_all( ModuleScope { name: AXL_ROOT_MODULE_NAME.to_string(), path: repo_root.clone(), }, configs.iter().map(|p| p.as_path()).collect(), tasks, ) .into_diagnostic()?; // Get updated list of tasks after evaluating all config functions. let tasks = config.tasks(); // Build the command tree from the evaluated and configured tasks. let mut tree = CommandTree::default(); // Create the base Clap command for the 'aspect' CLI. // TODO: add .about() let cmd = Command::new("aspect") // set binary name to "aspect" in help .bin_name("aspect") // add an about string .about("Aspect's programmable task runner built on top of Bazel\n{ Correct, Fast, Usable } -- Choose three") // customize the subcommands section title to "Tasks:" .subcommand_help_heading("Tasks") // customize the usage string to use <TASK> .subcommand_value_name("TASK") // handle --version and -v flags .version(cargo_pkg_short_version()) .disable_version_flag(true) // disable auto -V / --version .arg( Arg::new("version") .short('v') .long("version") .action(ArgAction::Version) .help("Print version"), ) // add version command .subcommand( Command::new("version") .about("Print version") .display_order(BUILTIN_COMMAND_DISPLAY_ORDER), ); // Convert each task into a Clap subcommand and insert into the command tree. for (i, task) in tasks.iter().enumerate() { let name = task.name.borrow(); let def = task.as_task().unwrap(); let group = def.group(); let task_path = PathBuf::from(task.path.clone()); let rel_path = match task_path.strip_prefix(&repo_root) { Ok(p) => p, Err(_) => &task_path, }; let mut found = None; for (module_name, module_root, _) in &use_task_modules { if task_path.starts_with(module_root) { if module_name == AXL_ROOT_MODULE_NAME { continue; } let module_rel_path = match task_path.strip_prefix(&module_root) { Ok(p) => p, Err(_) => &task_path, }; found = Some((module_name.clone(), module_rel_path.to_path_buf())); break; } } let defined_in = if let Some((module_name, rel_path)) = found { format!("@{}//{}", module_name, rel_path.display()) } else { format!("{}", rel_path.display()) }; let cmd = make_command_from_task(&name.to_string(), &defined_in, i.to_string(), def); tree.insert(&name, group, group, &defined_in, cmd) .into_diagnostic()?; } // Convert the command tree into a full Clap command with subcommands. let cmd = tree.as_command(cmd, &[]).into_diagnostic()?; // Parse command-line arguments against the Clap command structure. let matches = match cmd.try_get_matches() { Ok(m) => m, Err(err) => { err.print().into_diagnostic()?; return Ok(ExitCode::from(err.exit_code() as u8)); } }; // Handle the built-in 'version' subcommand if present. if let Some("version") = matches.subcommand_name() { println!("Aspect CLI {:}", cargo_pkg_version()); return Ok(ExitCode::SUCCESS); } // Extract the deepest subcommand from the matches (drilling down through groups). let mut cmd = matches.subcommand().expect("failed to get command"); while let Some(subcmd) = cmd.1.subcommand() { cmd = subcmd; } // Get the task name and arguments from the final subcommand. let (name, cmdargs) = cmd; let id: usize = tree.get_task_id(&cmdargs); let task = tasks.get(id).expect("task must exist at the indice"); let definition = task.as_task().unwrap(); // Enter a tracing span for task execution. let span = info_span!("task", name = name); let _enter = span.enter(); // Create an AxlStore for task execution let store = axl_loader.new_store(task.path.clone()); // Execute the selected task, passing in parsed arguments. let exit_code = task .module .execute_task(store, task, |heap| { let mut args = TaskArgs::new(); for (k, v) in definition.args().iter() { let val = match v { TaskArg::String { .. } => heap .alloc_str( cmdargs .get_one::<String>(k.as_str()) .unwrap_or(&String::new()), ) .to_value(), TaskArg::Int { .. } => heap .alloc(cmdargs.get_one::<i32>(k.as_str()).unwrap_or(&0).to_owned()) .to_value(), TaskArg::UInt { .. } => heap .alloc(cmdargs.get_one::<u32>(k.as_str()).unwrap_or(&0).to_owned()) .to_value(), TaskArg::Boolean { .. } => heap.alloc( cmdargs .get_one::<bool>(k.as_str()) .unwrap_or(&false) .to_owned(), ), TaskArg::Positional { .. } => heap.alloc(TaskArgs::alloc_list( cmdargs .get_many::<String>(k.as_str()) .map_or(vec![], |f| f.map(|s| s.as_str()).collect()), )), TaskArg::TrailingVarArgs => heap.alloc(TaskArgs::alloc_list( cmdargs .get_many::<String>(k.as_str()) .map_or(vec![], |f| f.map(|s| s.as_str()).collect()), )), TaskArg::StringList { .. } => heap.alloc(TaskArgs::alloc_list( cmdargs .get_many::<String>(k.as_str()) .unwrap_or_default() .map(|s| s.as_str()) .collect::<Vec<_>>(), )), TaskArg::BooleanList { .. } => heap.alloc(TaskArgs::alloc_list( cmdargs .get_many::<bool>(k.as_str()) .unwrap_or_default() .cloned() .collect::<Vec<_>>(), )), TaskArg::IntList { .. } => heap.alloc(TaskArgs::alloc_list( cmdargs .get_many::<i32>(k.as_str()) .unwrap_or_default() .cloned() .collect::<Vec<_>>(), )), TaskArg::UIntList { .. } => heap.alloc(TaskArgs::alloc_list( cmdargs .get_many::<u32>(k.as_str()) .unwrap_or_default() .cloned() .collect::<Vec<_>>(), )), }; args.insert(k.clone(), val); } args }) .into_diagnostic()?; return Ok(ExitCode::from(exit_code.unwrap_or(0))); }); // Await the blocking task result and handle any join errors. match out.await { Ok(err) => { drop(_root); drop(_tracing); err } Err(err) => panic!("{:?}", err), } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-docgen/src/highlight.rs
crates/axl-docgen/src/highlight.rs
use anyhow::Result; use markdown::mdast; use mdast_util_to_markdown::to_markdown; use regex::Regex; use syntect::html::{ClassStyle, ClassedHTMLGenerator}; use syntect::parsing::SyntaxSet; use syntect::util::LinesWithEndings; const PREDULE: &'static str = r#"<pre class="language-python"><code>"#; const POSTDULE: &'static str = r#"</code></pre>"#; pub fn highlight(md: &String) -> Result<String> { let mut md = markdown::to_mdast(md.as_str(), &markdown::ParseOptions::default()).unwrap(); fn traverse(nodes: &mut Vec<mdast::Node>) { let regex = Regex::new(r"(?m)@link@ ([\w/]+) @@ ([\w\.]+) @link@").unwrap(); nodes.iter_mut().for_each(|node| match node { mdast::Node::Html(html) => { let html_raw = html.value.clone(); if html_raw.starts_with(PREDULE) && html_raw.ends_with(POSTDULE) { let strip_down = html_raw .strip_prefix(PREDULE) .unwrap() .strip_suffix(POSTDULE) .unwrap(); let syntax_set = SyntaxSet::load_defaults_newlines(); let syntax_starlark = syntax_set.find_syntax_by_extension("py").unwrap(); let mut html_generator = ClassedHTMLGenerator::new_with_class_style( syntax_starlark, &syntax_set, ClassStyle::Spaced, ); for line in LinesWithEndings::from(strip_down) { html_generator .parse_html_for_line_which_includes_newline(line) .unwrap(); } let out = html_generator.finalize(); let out = regex.replace_all(out.as_str(), r#"<a href="$1">$2</a>"#); html.value = format!("{}{}{}", PREDULE, out, POSTDULE); } } mdast::Node::Heading(head) => traverse(&mut head.children), _ => {} }); } traverse(md.children_mut().unwrap()); Ok(md .children() .unwrap() .iter() .map(|node| to_markdown(node).unwrap()) .collect::<Vec<String>>() .join("\n")) } #[cfg(test)] mod tests { use super::highlight; #[test] fn test_syntax_highlight_with_links() -> anyhow::Result<()> { let out = highlight( &r#" ## task <pre class="language-python"><code>def task( *, name: '@link@ /lib/str @@ str @link@' = ..., implementation: typing.Callable[['@link@ /lib/task_context @@ task_context @link@'], None], args: dict['@link@ /lib/str @@ str @link@', '@link@ /lib/task_arg @@ task_arg @link@'], description: '@link@ /lib/str @@ str @link@' = ..., ) -> Task</code></pre> Task type representing a Task. ```python def _task_impl(ctx): pass build = name = "build", impl = _task_impl, task_args = { "target": args.string(), } ) ``` --- "# .to_string(), )?; assert_eq!(out, "test"); Ok(()) } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/axl-docgen/src/main.rs
crates/axl-docgen/src/main.rs
mod highlight; use anyhow::{Ok, Result}; use axl_runtime::eval; use starlark::docs::multipage::{render_markdown_multipage, DocModuleInfo}; use std::collections::HashMap; use std::fs; use std::path::PathBuf; fn snake(s: &str) -> String { let mut result = String::new(); let mut chars = s.chars().peekable(); while let Some(c) = chars.next() { if c.is_ascii_uppercase() { // Add an underscore before a new word, unless it's the very first character if !result.is_empty() && result.chars().last().unwrap() != '_' { result.push('_'); } result.push(c.to_ascii_lowercase()); } else { result.push(c); } } result } #[tokio::main] async fn main() -> Result<()> { println!("generating docs"); let task = eval::get_globals().build().documentation(); let modules_info = DocModuleInfo { module: &task, name: "lib".to_owned(), page_path: "lib".to_owned(), }; // Normalize index modules to be at the root. // Eg if a path is /lib/std/std then it should be just /lib/std // since we don't want to generate the index pages. fn normalize_path(path: &str) -> String { let paths = path.split("/").map(snake).collect::<Vec<String>>(); if path != "lib" && paths.len() > 2 && paths.last() == paths.get(paths.len() - 2) { paths[0..paths.len() - 1].join("/") } else { paths.join("/") } } fn deduplicate_keeping_with_more_docs<'v>( tuples: Vec<(&'v String, &'v String)>, ) -> Vec<(String, &'v String)> { let mut map: HashMap<String, &String> = HashMap::new(); // Insert tuples, keeping the last value for duplicate keys for (key, value) in tuples { let k = normalize_path(key.as_str()); if let Some(oldval) = map.get(k.as_str()) { if oldval.len() < value.len() { map.insert(k, value); } } else { map.insert(k, value); } } // Convert HashMap back to Vec map.into_iter().collect() } fn linked_ty_mapper(path: &str, type_name: &str) -> String { let path = normalize_path(path); format!(r#"'@link@ /{path} @@ {type_name} @link@'"#) } let res = render_markdown_multipage(vec![modules_info], Some(linked_ty_mapper)); let res = res .iter() .map(|(k, v)| (k, v)) .collect::<Vec<(&String, &String)>>(); let mut res = deduplicate_keeping_with_more_docs(res); res.sort_by(|(ka, _), (kb, _)| ka.cmp(kb)); fs::remove_dir_all("../../docs/lib")?; for (k, v) in res { let p = PathBuf::from(format!("../../docs/{k}.md")); if !p.parent().unwrap().exists() { fs::create_dir_all(p.parent().unwrap())?; } // Remove the first # in the markdown. let mut value = highlight::highlight(v)?; let value = value.split_off(value.find("\n").unwrap()); eprintln!("docs/{k}.md"); std::fs::write(format!("../../docs/{k}.md"), value).unwrap() } Ok(()) }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/starbuf-types/src/lib.rs
crates/starbuf-types/src/lib.rs
use prost_types::{Duration, Timestamp}; #[derive( ::starlark::values::ProvidesStaticType, ::derive_more::Display, ::starlark::values::Trace, ::starlark::values::NoSerialize, ::allocative::Allocative, Debug, )] #[display("Duration")] pub struct SBDuration(#[allocative(skip)] pub Duration); #[starlark::values::starlark_value(type = "duration")] impl<'v> starlark::values::StarlarkValue<'v> for SBDuration {} #[derive( ::starlark::values::ProvidesStaticType, ::derive_more::Display, ::starlark::values::Trace, ::starlark::values::NoSerialize, ::allocative::Allocative, Debug, )] #[display("Timestamp")] pub struct SBTimestamp(#[allocative(skip)] pub Timestamp); #[starlark::values::starlark_value(type = "Timestamp")] impl<'v> starlark::values::StarlarkValue<'v> for SBTimestamp {}
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false
aspect-build/aspect-cli
https://github.com/aspect-build/aspect-cli/blob/683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee/crates/pty-multiplex/src/main.rs
crates/pty-multiplex/src/main.rs
use std::{ fmt, fs, io::{self, BufWriter, Read, Write}, path::PathBuf, process::exit, sync::{ atomic::{AtomicBool, Ordering}, Arc, Mutex, RwLock, }, time::Duration, }; use bytes::Bytes; use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers}; use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize}; use ratatui::{ layout::Rect, style::{Color, Style, Stylize}, text::Line, widgets::{Block, BorderType, Borders, Padding}, DefaultTerminal, }; use std::collections::HashMap; use tokio::{ sync::mpsc::{channel, Sender}, task::spawn_blocking, }; use tracing::Level; use tracing_subscriber::FmtSubscriber; use tui_term::vt100; use tui_term::widget::{Cursor, PseudoTerminal}; #[derive(Debug)] struct Spawn { program: String, title: String, current_dir: String, args: Vec<String>, env: HashMap<String, String>, } #[derive(Debug, Clone, Copy)] struct Size { cols: u16, rows: u16, } fn parse_args(args: impl Iterator<Item = String>) -> Vec<Spawn> { let mut invocations = Vec::new(); let mut current: Option<Spawn> = None; let mut args = args.skip(1); // Skip the binary name while let Some(arg) = args.next() { match arg.as_str() { "--spawn" => { if let Some(inv) = current.take() { invocations.push(inv); } if let Some(program) = args.next() { current = Some(Spawn { program: program.clone(), title: program, current_dir: std::env::current_dir() .unwrap() .to_string_lossy() .to_string(), args: Vec::new(), env: HashMap::new(), }); } else { panic!("--spawn requires value") } } "--title" => { if let Some(inv) = current.as_mut() { if let Some(title) = args.next() { inv.title = title; } else { panic!("--title requires value") } } else { panic!("--title requires a preceding --spawn") } } "--current_dir" => { if let Some(inv) = current.as_mut() { if let Some(dir) = args.next() { inv.current_dir = dir; } else { panic!("--current_dir requires value") } } else { panic!("--current_dir requires a preceding --spawn") } } "--env" => { if let Some(inv) = current.as_mut() { if let Some(env_str) = args.next() { let mut parts = env_str.splitn(2, '='); if let (Some(key), Some(val)) = (parts.next(), parts.next()) { inv.env.insert(key.to_string(), val.to_string()); } else { panic!("--env requires value") } } } else { panic!("--env requires a preceding --spawn") } } "--arg" => { if let Some(inv) = current.as_mut() { if let Some(arg_val) = args.next() { inv.args.push(arg_val); } else { panic!("--arg requires value") } } else { panic!("--arg requires a preceding --spawn") } } arg => { panic!("unexpected arg {}", arg) } } } if let Some(inv) = current.take() { invocations.push(inv); } invocations } #[tokio::main] async fn main() -> std::io::Result<()> { init_panic_hook(); let args = std::env::args(); if args.len() < 2 { eprintln!("pass --spawn argument and --env --arg after --spawn"); exit(1); } let spawns = parse_args(args); let mut terminal = ratatui::init(); let result = run_smux(&mut terminal, spawns).await; ratatui::restore(); result } async fn run_smux(terminal: &mut DefaultTerminal, spawns: Vec<Spawn>) -> io::Result<()> { let mut size = Size { rows: terminal.size()?.height, cols: terminal.size()?.width, }; let mut panes: Vec<PtyPane> = Vec::new(); let mut active_pane: Option<usize> = None; let pane_size = calc_pane_size(size, spawns.len()); for spawn in spawns.into_iter() { let mut cmd = CommandBuilder::new(spawn.program); cmd.args(spawn.args); cmd.cwd(spawn.current_dir); for (k, v) in spawn.env { cmd.env(k, v); } open_new_pane(spawn.title, &mut panes, &mut active_pane, &cmd, pane_size)?; } loop { terminal.draw(|f| { let area = f.area(); let pane_width = if panes.is_empty() { area.width } else { area.width / panes.len() as u16 }; for (index, pane) in panes.iter().enumerate() { let title = Line::from(format!(" {} ", pane.title)); let block = Block::default() .borders(Borders::all()) .border_type(BorderType::Rounded) .padding(Padding::new(1, 1, 1, 1)) .title(title) .style(Style::default().bold().dim()); let mut cursor = Cursor::default(); let block = if Some(index) == active_pane { block.style(Style::default().bold().fg(Color::LightGreen)) } else { cursor.hide(); block }; let parser = pane.parser.read().unwrap(); let screen = parser.screen(); let pseudo_term = PseudoTerminal::new(screen).block(block).cursor(cursor); let pane_chunk = Rect { // Adjust the x coordinate for each pane x: area.x + (index as u16 * pane_width), y: area.y, // Use the calculated pane width directly width: pane_width, height: area.height, }; f.render_widget(pseudo_term, pane_chunk); } })?; if event::poll(Duration::from_millis(10))? { tracing::info!("terminal Size: {:?}", terminal.size()); match event::read()? { Event::Key(key) => match key.code { KeyCode::Char('q') if key.modifiers.contains(KeyModifiers::CONTROL) => { return Ok(()); } _ => { if let Some(index) = active_pane { if handle_pane_key_event(&mut panes[index], &key).await { continue; } } } }, Event::Resize(cols, rows) => { tracing::info!("resized to: rows: {} cols: {}", rows, cols); size.rows = rows; size.cols = cols; let pane_size = calc_pane_size(size, panes.len()); resize_all_panes(&mut panes, pane_size); } _ => {} } } cleanup_exited_panes(&mut panes, &mut active_pane); if panes.is_empty() { return Ok(()); } } } fn cleanup_exited_panes(panes: &mut Vec<PtyPane>, active_pane: &mut Option<usize>) { let mut i = 0; while i < panes.len() { if !panes[i].is_alive() { let _removed_pane = panes.remove(i); if let Some(active) = active_pane { match (*active).cmp(&i) { std::cmp::Ordering::Greater => { *active = active.saturating_sub(1); } std::cmp::Ordering::Equal => { if panes.is_empty() { *active_pane = None; } else if i >= panes.len() { *active_pane = Some(panes.len() - 1); } } std::cmp::Ordering::Less => {} } } } else { i += 1; } } } fn calc_pane_size(mut size: Size, nr_panes: usize) -> Size { // size.cols -= 2; size.cols /= nr_panes as u16; size } fn resize_all_panes(panes: &mut [PtyPane], size: Size) { for pane in panes.iter() { pane.resize(size); } } struct PtyPane { title: String, parser: Arc<RwLock<vt100::Parser>>, sender: Sender<Bytes>, master_pty: Box<dyn MasterPty>, exited: Arc<AtomicBool>, } impl PtyPane { fn new(title: String, size: Size, cmd: CommandBuilder) -> io::Result<Self> { let pty_system = native_pty_system(); let pty_pair = pty_system .openpty(PtySize { rows: size.rows - 4, cols: size.cols - 4, pixel_width: 0, pixel_height: 0, }) .unwrap(); let parser = Arc::new(RwLock::new(vt100::Parser::new( size.rows - 4, size.cols - 4, 0, ))); let exited = Arc::new(AtomicBool::new(false)); { let exited_clone = exited.clone(); spawn_blocking(move || { let mut child = pty_pair.slave.spawn_command(cmd).unwrap(); let _ = child.wait(); exited_clone.store(true, Ordering::Relaxed); drop(pty_pair.slave); }); } { let mut reader = pty_pair.master.try_clone_reader().unwrap(); let parser = parser.clone(); tokio::spawn(async move { let mut processed_buf = Vec::new(); let mut buf = [0u8; 8192]; loop { let size = reader.read(&mut buf).unwrap(); if size == 0 { break; } if size > 0 { processed_buf.extend_from_slice(&buf[..size]); let mut parser = parser.write().unwrap(); parser.process(&processed_buf); // Clear the processed portion of the buffer processed_buf.clear(); } } }); } let (tx, mut rx) = channel::<Bytes>(32); let mut writer = BufWriter::new(pty_pair.master.take_writer().unwrap()); // writer is moved into the tokio task below tokio::spawn(async move { while let Some(bytes) = rx.recv().await { writer.write_all(&bytes).unwrap(); writer.flush().unwrap(); } }); Ok(Self { title, parser, sender: tx, master_pty: pty_pair.master, exited, }) } fn resize(&self, size: Size) { self.parser .write() .unwrap() .set_size(size.rows - 4, size.cols - 4); self.master_pty .resize(PtySize { rows: size.rows - 4, cols: size.cols - 4, pixel_width: 0, pixel_height: 0, }) .unwrap(); } fn is_alive(&self) -> bool { !self.exited.load(Ordering::Relaxed) } } async fn handle_pane_key_event(pane: &mut PtyPane, key: &KeyEvent) -> bool { let input_bytes = match key.code { KeyCode::Char(ch) => { let mut send = vec![ch as u8]; let upper = ch.to_ascii_uppercase(); if key.modifiers == KeyModifiers::CONTROL { match upper { 'N' => { // Ignore Ctrl+n within a pane return true; } 'X' => { // Close the pane return false; } // https://github.com/fyne-io/terminal/blob/master/input.go // https://gist.github.com/ConnerWill/d4b6c776b509add763e17f9f113fd25b '2' | '@' | ' ' => send = vec![0], '3' | '[' => send = vec![27], '4' | '\\' => send = vec![28], '5' | ']' => send = vec![29], '6' | '^' => send = vec![30], '7' | '-' | '_' => send = vec![31], char if ('A'..='_').contains(&char) => { // Since A == 65, // we can safely subtract 64 to get // the corresponding control character let ascii_val = char as u8; let ascii_to_send = ascii_val - 64; send = vec![ascii_to_send]; } _ => {} } } send } #[cfg(unix)] KeyCode::Enter => vec![b'\n'], #[cfg(windows)] KeyCode::Enter => vec![b'\r', b'\n'], KeyCode::Backspace => vec![8], KeyCode::Left => vec![27, 91, 68], KeyCode::Right => vec![27, 91, 67], KeyCode::Up => vec![27, 91, 65], KeyCode::Down => vec![27, 91, 66], KeyCode::Tab => vec![9], KeyCode::Home => vec![27, 91, 72], KeyCode::End => vec![27, 91, 70], KeyCode::PageUp => vec![27, 91, 53, 126], KeyCode::PageDown => vec![27, 91, 54, 126], KeyCode::BackTab => vec![27, 91, 90], KeyCode::Delete => vec![27, 91, 51, 126], KeyCode::Insert => vec![27, 91, 50, 126], KeyCode::Esc => vec![27], _ => return true, }; pane.sender.send(Bytes::from(input_bytes)).await.ok(); true } fn open_new_pane( title: String, panes: &mut Vec<PtyPane>, active_pane: &mut Option<usize>, cmd: &CommandBuilder, size: Size, ) -> io::Result<()> { let new_pane = PtyPane::new(title, size, cmd.clone())?; let new_pane_index = panes.len(); panes.push(new_pane); *active_pane = Some(new_pane_index); Ok(()) } fn init_panic_hook() { let log_file = Some(PathBuf::from("/tmp/cli2-pty-mux.log")); let log_file = match log_file { Some(path) => { if let Some(parent) = path.parent() { let _ = fs::create_dir_all(parent); } Some(fs::File::create(path).unwrap()) } None => None, }; let subscriber = FmtSubscriber::builder() // all spans/events with a level higher than TRACE (e.g, debug, info, warn, etc.) // will be written to output path. .with_max_level(Level::TRACE) .with_writer(Mutex::new(log_file.unwrap())) .with_thread_ids(true) .with_ansi(true) .with_line_number(true); let subscriber = subscriber.finish(); tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed"); // Set the panic hook to log panic information before panicking std::panic::set_hook(Box::new(|panic| { let original_hook = std::panic::take_hook(); tracing::error!("panic error: {}", panic); ratatui::restore(); original_hook(panic); })); tracing::debug!("set panic hook") } impl fmt::Debug for PtyPane { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let parser = self.parser.read().unwrap(); let screen = parser.screen(); f.debug_struct("PtyPane") .field("screen", screen) .field("title:", &screen.title()) .field("icon_name:", &screen.icon_name()) .finish() } }
rust
Apache-2.0
683f7133a97bd2edb6ffb54569c3bb2a3c4e7eee
2026-01-04T20:17:03.553553Z
false