-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathdistrobox.rs
More file actions
1781 lines (1606 loc) · 60.6 KB
/
distrobox.rs
File metadata and controls
1781 lines (1606 loc) · 60.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::fakers::{Child, Command, CommandRunner, FdMode, NullCommandRunnerBuilder};
use serde::{Deserialize, Deserializer};
use std::{
cell::LazyCell,
collections::{BTreeMap, HashMap},
ffi::OsString,
io,
os::unix::ffi::OsStringExt,
path::{Path, PathBuf},
process::Output,
rc::Rc,
str::FromStr,
};
use tracing::{debug, error, info, warn};
use crate::backends::desktop_file::*;
use crate::backends::distrobox::command::{CmdFactory, default_cmd_factory};
const POSIX_FIND_AND_CONCAT_DESKTOP_FILES: &str =
include_str!("POSIX_FIND_AND_CONCAT_DESKTOP_FILES.sh");
/// Encode a string as hex (matching the shell script's base16 function)
fn to_hex(s: &str) -> String {
s.bytes().map(|b| format!("{:02x}", b)).collect()
}
#[derive(Deserialize, Debug)]
struct DesktopFiles {
#[serde(deserialize_with = "DesktopFiles::deserialize_path")]
home_dir: PathBuf,
#[serde(deserialize_with = "DesktopFiles::deserialize_desktop_files")]
system: BTreeMap<PathBuf, String>,
#[serde(deserialize_with = "DesktopFiles::deserialize_desktop_files")]
user: BTreeMap<PathBuf, String>,
}
impl DesktopFiles {
fn decode_hex<E: serde::de::Error>(hex_str: &str) -> Result<Vec<u8>, E> {
if !hex_str.len().is_multiple_of(2) {
return Err(E::invalid_length(
hex_str.len(),
&"hex string to have an even length",
));
}
(0..hex_str.len())
.step_by(2)
.map(|i| u8::from_str_radix(&hex_str[i..=i + 1], 16))
.collect::<Result<_, _>>()
.map_err(|e| {
E::custom(format_args!(
"hex string contains non hex characters: {e:?}"
))
})
}
fn decode_utf8_from_hex<E: serde::de::Error>(hex_str: &str) -> Result<String, E> {
String::from_utf8(Self::decode_hex(hex_str)?).map_err(|e| {
E::custom(format_args!(
"decoded hex string does not represent valid UTF-8: {e:?}"
))
})
}
fn decode_path_from_hex<E: serde::de::Error>(hex_str: &str) -> Result<PathBuf, E> {
Ok(PathBuf::from(OsString::from_vec(Self::decode_hex(
hex_str,
)?)))
}
fn deserialize_path<'de, D: Deserializer<'de>>(deserializer: D) -> Result<PathBuf, D::Error> {
Self::decode_path_from_hex(&String::deserialize(deserializer)?)
}
fn deserialize_desktop_files<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<BTreeMap<PathBuf, String>, D::Error> {
BTreeMap::<String, String>::deserialize(deserializer)?
.into_iter()
.map(|(path, content)| {
Ok((
Self::decode_path_from_hex(&path)?,
Self::decode_utf8_from_hex(&content)?,
))
})
.collect()
}
fn into_map(self, host_home: Option<PathBuf>) -> BTreeMap<PathBuf, String> {
let mut desktop_files = self.system;
// Only include user desktop files if the container's home directory is different from the host's
// This avoids showing duplicate entries when the container shares the host's home directory
if host_home.as_ref() != Some(&self.home_dir) {
desktop_files.extend(self.user)
}
desktop_files
}
}
pub struct Distrobox {
cmd_runner: CommandRunner,
cmd_factory: CmdFactory,
}
type CommandResponse = (Command, Rc<dyn Fn() -> io::Result<String>>);
#[derive(Clone, Debug, PartialEq, Hash)]
pub enum Status {
Up(String),
Created(String),
Exited(String),
// I don't want the app to crash if the parsing fails because distrobox changed with an update.
// We will just disable some features, but still show the status value.
Other(String),
}
impl Default for Status {
fn default() -> Self {
Self::Other("".into())
}
}
impl std::fmt::Display for Status {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Status::Up(s) => write!(f, "Up {}", s),
Status::Created(s) => write!(f, "Created {}", s),
Status::Exited(s) => write!(f, "Exited {}", s),
Status::Other(s) => write!(f, "{}", s),
}
}
}
impl Status {
fn from_str(s: &str) -> Self {
if let Some(rest) = s.strip_prefix("Up") {
Status::Up(rest.trim().to_string())
} else if let Some(rest) = s.strip_prefix("Exited") {
Status::Exited(rest.trim().to_string())
} else if let Some(rest) = s.strip_prefix("Created") {
Status::Created(rest.trim().to_string())
} else {
Status::Other(s.to_string())
}
}
}
#[derive(Debug, PartialEq, Hash, Clone)]
pub struct ContainerInfo {
pub id: String,
pub name: String,
pub status: Status,
pub image: String,
}
impl ContainerInfo {
fn field_missing_error(text: &str, line: &str) -> Error {
Error::ParseOutput(format!("{text} missing in line: {}", line))
}
}
impl FromStr for ContainerInfo {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<&str> = s.split('|').collect();
if parts.len() != 4 {
return Err(Error::ParseOutput(format!(
"Invalid field count (expected 4, got {}) in line: {}",
parts.len(),
s
)));
}
let id = parts[0].trim();
let name = parts[1].trim();
let status = parts[2].trim();
let image = parts[3].trim();
// Check for empty fields
if id.is_empty() {
return Err(ContainerInfo::field_missing_error("id", s));
}
if name.is_empty() {
return Err(ContainerInfo::field_missing_error("name", s));
}
if status.is_empty() {
return Err(ContainerInfo::field_missing_error("status", s));
}
if image.is_empty() {
return Err(ContainerInfo::field_missing_error("image", s));
}
Ok(ContainerInfo {
id: id.to_string(),
name: name.to_string(),
status: Status::from_str(status),
image: image.to_string(),
})
}
}
#[derive(Debug, Clone)]
pub struct ExportableApp {
pub entry: DesktopEntry,
pub desktop_file_path: String,
pub exported: bool,
}
#[derive(Debug, Clone)]
pub struct ExportableBinary {
pub name: String,
pub source_path: String,
pub exported_path: String,
}
#[derive(Default, Debug, PartialEq, Clone)]
pub struct CreateArgName(String);
impl std::fmt::Display for CreateArgName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl CreateArgName {
pub fn new(value: &str) -> Result<Self, InvalidValue> {
let re = regex::Regex::new(r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$").unwrap();
if re.is_match(value) {
Ok(CreateArgName(value.to_string()))
} else {
Err(InvalidValue {
hint: "Must respect the format [a-zA-Z0-9][a-zA-Z0-9_.-]*".into(),
})
}
}
}
#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
pub struct CreateArgsImage(String);
impl CreateArgsImage {
pub fn new(value: &str) -> Result<Self, InvalidValue> {
if value.trim().is_empty() {
Err(InvalidValue {
hint: "Image cannot be empty".into(),
})
} else {
Ok(CreateArgsImage(value.to_string()))
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for CreateArgsImage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Default, Debug, PartialEq, Clone)]
pub struct CreateArgs {
pub init: bool,
pub nvidia: bool,
pub root: bool,
pub no_entry: bool,
pub hostname: Option<String>,
pub home_path: Option<String>,
pub image: Option<CreateArgsImage>,
pub name: CreateArgName,
pub volumes: Vec<Volume>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum VolumeMode {
ReadOnly,
}
impl std::fmt::Display for VolumeMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
VolumeMode::ReadOnly => write!(f, "ro"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Volume {
pub host_path: String,
pub container_path: String,
pub mode: Option<VolumeMode>,
}
impl FromStr for Volume {
type Err = InvalidValue;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<&str> = s.split(':').collect();
match parts.as_slice() {
[host] => Ok(Volume {
host_path: host.to_string(),
container_path: host.to_string(),
mode: None,
}),
[host, target] => Ok(Volume {
host_path: host.to_string(),
container_path: target.to_string(),
mode: None,
}),
[host, target, "ro"] => Ok(Volume {
host_path: host.to_string(),
container_path: target.to_string(),
mode: Some(VolumeMode::ReadOnly),
}),
_ => Err(InvalidValue {
hint: format!("Invalid volume descriptor: {}", s),
}),
}
}
}
impl std::fmt::Display for Volume {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}", self.host_path, self.container_path)?;
if let Some(mode) = &self.mode {
write!(f, ":{}", mode)?;
}
Ok(())
}
}
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("failed to read command stdout: {0}")]
StdoutRead(#[from] io::Error),
#[error("failed to spawn command {command}: {source}")]
Spawn { source: io::Error, command: String },
#[error("failed to parse command output: {0}")]
ParseOutput(String),
#[error("{0}")]
InvalidValue(#[from] InvalidValue),
#[error("command failed with exit code {exit_code:?}: {command}\n{stderr}")]
CommandFailed {
exit_code: Option<i32>,
command: String,
stderr: String,
},
#[error("failed to resolve host path: {0}. getfattr may not be installed on the host")]
ResolveHostPath(String),
}
#[derive(thiserror::Error, Debug)]
#[error("invalid value: {hint}")]
pub struct InvalidValue {
pub hint: String,
}
/// Represents mock responses for the NullCommandRunner used in previews and testing.
///
/// These responses simulate the output of various distrobox commands without
/// actually executing them. This is essential for:
/// - UI previews in development (via DistroboxStoreTy::NullWorking)
/// - Unit testing without requiring a real distrobox installation
/// - Flatpak sandbox testing
#[derive(Clone)]
pub enum DistroboxCommandRunnerResponse {
/// Mock response for `distrobox version` command
/// Returns a successful version string like "distrobox: 1.7.2.1"
Version,
/// Mock response for when distrobox is not installed
/// Returns an error when version is queried
NoVersion,
/// Mock response for `distrobox ls --no-color` command
/// Returns a list of containers in the expected pipe-delimited format
List(Vec<ContainerInfo>),
/// Mock response for `distrobox create --compatibility` command
/// Returns a list of compatible container images
Compatibility(Vec<String>),
/// Mock response for listing exportable applications from a container
/// Contains: (distrobox_name, [(filename, app_name, icon_name)])
/// Generates the TOML hex-encoded format expected by the desktop file parser
ExportedApps(String, Vec<(String, String, String)>),
}
impl DistroboxCommandRunnerResponse {
pub fn common_distros() -> LazyCell<Vec<ContainerInfo>> {
LazyCell::new(|| {
[
("1", "Ubuntu", "docker.io/library/ubuntu:latest"),
("2", "Fedora", "docker.io/library/fedora:latest"),
("3", "Kali", "docker.io/kalilinux/kali-rolling"),
("4", "Debian", "docker.io/library/debian:latest"),
("5", "Arch Linux", "docker.io/library/archlinux:latest"),
("6", "CentOS", "docker.io/library/centos:latest"),
("7", "Alpine", "docker.io/library/alpine:latest"),
("8", "OpenSUSE", "docker.io/library/opensuse:latest"),
("9", "Gentoo", "docker.io/library/gentoo:latest"),
("10", "Slackware", "docker.io/library/slackware:latest"),
("11", "Void Linux", "docker.io/library/voidlinux:latest"),
("13", "Deepin", "docker.io/library/deepin:latest"),
("16", "Rocky Linux", "docker.io/library/rockylinux:latest"),
(
"17",
"Crystal Linux",
"docker.io/library/crystal-linux:latest",
),
]
.iter()
.map(|(id, name, image)| ContainerInfo {
id: id.to_string(),
name: name.to_string(),
status: Status::Created("2 minutes ago".into()),
image: image.to_string(),
})
.collect()
})
}
pub fn new_list_common_distros() -> Self {
Self::List(Self::common_distros().to_owned())
}
pub fn new_common_exported_apps() -> Self {
let dummy_exported_apps = vec![
("vim.desktop".into(), "Vim".into(), "vim".into()),
("matlab.desktop".into(), "MATLAB".into(), "matlab".into()),
(
"vscode.desktop".into(),
"Visual Studio Code".into(),
"code".into(),
),
("rstudio.desktop".into(), "RStudio".into(), "rstudio".into()),
(
"sublime_text.desktop".into(),
"Sublime Text".into(),
"subl".into(),
),
("zoom.desktop".into(), "Zoom".into(), "zoom".into()),
("slack.desktop".into(), "Slack".into(), "slack".into()),
("postman.desktop".into(), "Postman".into(), "postman".into()),
];
DistroboxCommandRunnerResponse::ExportedApps("Ubuntu".into(), dummy_exported_apps)
}
pub fn new_common_images() -> Self {
DistroboxCommandRunnerResponse::Compatibility(
Self::common_distros()
.iter()
.map(|x| x.image.clone())
.collect(),
)
}
fn build_version_response() -> (Command, String) {
let mut cmd = default_cmd_factory()();
cmd.arg("version");
(cmd, "distrobox: 1.7.2.1".to_string())
}
fn build_no_version_response() -> (Command, Rc<dyn Fn() -> io::Result<String>>) {
let mut cmd = default_cmd_factory()();
cmd.arg("version");
(cmd, Rc::new(|| Err(io::Error::from_raw_os_error(0))))
}
fn build_list_response(containers: &[ContainerInfo]) -> (Command, String) {
let mut output = String::new();
output.push_str("ID | NAME | STATUS | IMAGE \n");
for container in containers {
output.push_str(&container.id);
output.push_str(" | ");
output.push_str(&container.name);
output.push_str(" | ");
let status = container.status.to_string();
output.push_str(&format!("{status} | "));
output.push_str(&container.image);
output.push('\n');
}
let mut cmd = default_cmd_factory()();
cmd.arg("ls").arg("--no-color");
(cmd, output.clone())
}
fn build_compatibility_response(images: &[String]) -> (Command, String) {
let output = images.join("\n");
let mut cmd = default_cmd_factory()();
cmd.arg("create").arg("--compatibility");
(cmd, output)
}
fn build_exported_apps_commands(
box_name: &str,
apps: &[(String, String, String)],
) -> Vec<(Command, String)> {
let mut commands = Vec::new();
// Get XDG_DATA_HOME (mocked via printenv)
commands.push((
Command::new_with_args("printenv", ["XDG_DATA_HOME"]),
String::new(),
));
// Get HOME if XDG_DATA_HOME is empty (mocked via printenv)
commands.push((
Command::new_with_args("printenv", ["HOME"]),
"/home/me".to_string(),
));
// List desktop files - these are the exported files in the user's local applications folder
// Format: {box_name}-{filename}
let file_list = apps
.iter()
.map(|(filename, _, _)| format!("{box_name}-{}", filename))
.collect::<Vec<_>>()
.join("\n");
commands.push((
Command::new_with_args("ls", ["/home/me/.local/share/applications"]),
file_list,
));
// Build desktop files TOML with hex encoding (matching POSIX_FIND_AND_CONCAT_DESKTOP_FILES.sh output)
let mut toml = format!("home_dir=\"{}\"\n", to_hex("/home/me"));
toml.push_str("[system]\n");
for (filename, name, icon) in apps {
let path = format!("/usr/share/applications/{}", filename);
let content = format!(
"[Desktop Entry]\n\
Type=Application\n\
Name={}\n\
Exec=/path/to/{}\n\
Icon={}\n\
Categories=Utility;Network;",
name, name, icon
);
toml.push_str(&format!("\"{}\"=\"{}\"\n", to_hex(&path), to_hex(&content)));
}
toml.push_str("[user]\n");
let mut db_cmd = default_cmd_factory()();
db_cmd.args([
"enter",
box_name,
"--",
"sh",
"-c",
POSIX_FIND_AND_CONCAT_DESKTOP_FILES,
]);
commands.push((db_cmd, toml));
commands
}
fn wrap_err_fn(output: (Command, String)) -> CommandResponse {
(output.0, Rc::new(move || Ok(output.1.clone())))
}
pub fn into_commands(self) -> Vec<CommandResponse> {
match self {
Self::Version => {
let working_response = Self::build_version_response();
vec![Self::wrap_err_fn(working_response)]
}
Self::NoVersion => {
vec![Self::build_no_version_response()]
}
Self::List(containers) => {
vec![Self::wrap_err_fn(Self::build_list_response(&containers))]
}
Self::Compatibility(images) => vec![Self::wrap_err_fn(
Self::build_compatibility_response(&images),
)],
Self::ExportedApps(box_name, apps) => {
Self::build_exported_apps_commands(&box_name, &apps)
.into_iter()
.map(Self::wrap_err_fn)
.collect()
}
}
}
}
impl Distrobox {
// The command factory ensures we can customize the distrobox executable path, e.g. to use a bundled version.
pub fn new(cmd_runner: CommandRunner, cmd_factory: CmdFactory) -> Self {
Self {
cmd_runner,
cmd_factory,
}
}
fn dbcmd(&self) -> Command {
(self.cmd_factory)()
}
pub fn null_command_runner(responses: &[DistroboxCommandRunnerResponse]) -> CommandRunner {
let mut builder = NullCommandRunnerBuilder::new();
for res in responses {
for (cmd, out) in res.clone().into_commands() {
builder.cmd_full(cmd, move || out());
}
}
builder.build()
}
pub fn cmd_spawn(&self, mut cmd: Command) -> Result<Box<dyn Child + Send>, Error> {
cmd.stdout = FdMode::Pipe;
cmd.stderr = FdMode::Pipe;
let program = cmd.program.to_string_lossy().to_string();
let args = cmd
.args
.iter()
.map(|arg| arg.to_string_lossy().to_string())
.collect::<Vec<_>>();
debug!(command = %program, args = ?args, "Spawning command");
let child = self.cmd_runner.spawn(cmd.clone()).map_err(|e| {
let full_command = format!("{:?} {:?}", program, args);
error!(error = ?e, command = %full_command, "Command spawn failed");
Error::Spawn {
source: e,
command: full_command,
}
})?;
Ok(child)
}
async fn cmd_output(&self, mut cmd: Command) -> Result<Output, Error> {
cmd.stdout = FdMode::Pipe;
cmd.stderr = FdMode::Pipe;
let program = cmd.program.to_string_lossy().to_string();
let args = cmd
.args
.iter()
.map(|arg| arg.to_string_lossy().to_string())
.collect::<Vec<_>>();
info!(command = %program, args = ?args, "Executing command");
let command_str = format!("{:?} {:?}", program, args);
let output = self.cmd_runner.output(cmd).await.map_err(|e| {
error!(error = ?e, command = %program, "Command execution failed");
Error::Spawn {
source: e,
command: command_str.clone(),
}
})?;
let exit_code = output.status.code();
debug!(
exit_code = ?exit_code,
"Command completed successfully"
);
Ok(output)
}
async fn cmd_output_string(&self, cmd: Command) -> Result<String, Error> {
let command_str = format!("{:?} {:?}", cmd.program, cmd.args);
let output = self.cmd_output(cmd).await?;
let s = String::from_utf8_lossy(&output.stdout);
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
let exit_code = output.status.code();
error!(
exit_code = ?exit_code,
stderr = %stderr,
"Command failed"
);
return Err(Error::CommandFailed {
exit_code,
command: command_str,
stderr,
});
}
Ok(s.to_string())
}
async fn host_applications_path(
&self,
host_env: &HashMap<String, String>,
) -> Result<PathBuf, Error> {
let xdg_data_home_opt = host_env
.get("XDG_DATA_HOME")
.filter(|s| !s.trim().is_empty())
.map(|s| Path::new(s.trim()).to_path_buf());
let apps_base = if let Some(p) = xdg_data_home_opt {
p
} else {
// Fallback to HOME
match host_env.get("HOME").filter(|s| !s.trim().is_empty()) {
Some(s) => Path::new(s.trim()).join(".local/share"),
None => {
return Err(Error::ResolveHostPath(
"XDG_DATA_HOME and HOME are not set on the host".into(),
));
}
}
};
let apps_path = apps_base.join("applications");
Ok(apps_path)
}
async fn get_exported_desktop_files(
&self,
host_env: &HashMap<String, String>,
) -> Result<Vec<String>, Error> {
// We do everything with the command line to ensure we can access the files and environment variables
// even when inside a flatpak sandbox, with only the permissions to run `flatpak-spawn`
let mut cmd = Command::new("ls");
cmd.arg(self.host_applications_path(host_env).await?);
let ls_out = self.cmd_output_string(cmd).await?;
let apps = ls_out
.trim()
.split("\n")
.map(|app| app.to_string())
.collect::<Vec<_>>();
Ok(apps)
}
async fn get_desktop_files(
&self,
box_name: &str,
host_env: &HashMap<String, String>,
) -> Result<Vec<(String, String)>, Error> {
let mut cmd = self.dbcmd();
cmd.args([
"enter",
box_name,
"--",
"sh",
"-c",
POSIX_FIND_AND_CONCAT_DESKTOP_FILES,
]);
let desktop_files: DesktopFiles = toml::from_str(&self.cmd_output_string(cmd).await?)
.map_err(|e| Error::ParseOutput(format!("{e:?}")))?;
debug!(desktop_files = format_args!("{desktop_files:#?}"));
let host_home_opt = host_env.get("HOME").cloned().map(PathBuf::from);
Ok(desktop_files
.into_map(host_home_opt)
.into_iter()
.map(|(path, content)| (path.to_string_lossy().into_owned(), content))
.collect::<Vec<_>>())
}
pub async fn list_apps(&self, box_name: &str) -> Result<Vec<ExportableApp>, Error> {
let host_env = match crate::fakers::resolve_host_env(&self.cmd_runner).await {
Ok(env) => env,
Err(e) => {
tracing::warn!("failed to resolve host env via CommandRunner: {e:?}");
HashMap::new()
}
};
let files = self.get_desktop_files(box_name, &host_env).await?;
debug!(desktop_files=?files);
let exported = self.get_exported_desktop_files(&host_env).await?;
debug!(exported_files=?exported);
let res: Vec<ExportableApp> = files
.into_iter()
.flat_map(|(path, content)| -> Option<ExportableApp> {
let entry = match parse_desktop_file(&content) {
Ok(e) => e,
Err(e) => {
tracing::warn!("Failed to parse desktop file {}: {}", path, e);
return None;
}
};
let file_name = Path::new(&path)
.file_name()
.map(|x| x.to_str())
.unwrap_or_default()
.unwrap_or_default();
let exported_as = format!("{box_name}-{file_name}");
let is_exported = exported.contains(&exported_as);
if is_exported {
debug!(found_exported = exported_as);
}
Some(ExportableApp {
desktop_file_path: path,
entry,
exported: is_exported,
})
})
.collect();
Ok(res)
}
/// Lists only the binaries that have already been exported from the container.
pub async fn get_exported_binaries(
&self,
box_name: &str,
) -> Result<Vec<ExportableBinary>, Error> {
let mut cmd = self.dbcmd();
cmd.args([
"enter",
box_name,
"--",
"distrobox-export",
"--list-binaries",
]);
// Example output: '/usr/bin/vim' | /home/user/.local/bin/vim
let output = self.cmd_output_string(cmd).await?;
debug!(binaries_output = output);
let mut binaries = Vec::new();
for line in output.lines() {
if line.is_empty() || !line.contains('|') {
continue;
}
let parts: Vec<&str> = line.split('|').collect();
if parts.len() >= 2 {
let source_path = parts[0].trim().to_string();
// For some reason distrobox formats the source path between single quotes, so we need to remove those
let source_path = source_path.trim_matches('\'').to_string();
let exported_path_str = parts[1].trim();
// Only include binaries that have a non-empty exported path. It should always be the case, but BoxBuddy defensively checks it.
// In this case we try to follow BoxBuddy's behavior to keep consistency for users.
if !exported_path_str.is_empty() {
let exported_path = exported_path_str.to_string();
// If source_path is empty (due to a bug in distrobox's --list-binaries when
// sudo_prefix is not set, common in Arch Linux containers), try to extract
// the actual binary path from the exported wrapper script.
let source_path = if source_path.is_empty() {
self.extract_binary_path_from_wrapper(&exported_path)
.await
.unwrap_or_else(|| exported_path.clone())
} else {
source_path
};
// Extract binary name from source path, falling back to exported_path if source_path is still problematic.
let name = Path::new(&source_path)
.file_name()
.and_then(|n| n.to_str())
.filter(|s| !s.is_empty())
.or_else(|| {
Path::new(&exported_path)
.file_name()
.and_then(|n| n.to_str())
})
.unwrap_or(&source_path)
.to_string();
binaries.push(ExportableBinary {
name,
source_path,
exported_path,
});
}
}
}
Ok(binaries)
}
/// Extracts the original binary path from a distrobox exported wrapper script.
/// The wrapper script contains lines like: exec '/usr/bin/binary' "$@"
///
/// Uses the shared `extract_quoted_string` utility from desktop_file module for
/// consistent string parsing across the codebase.
async fn extract_binary_path_from_wrapper(&self, wrapper_path: &str) -> Option<String> {
// Read the wrapper script content
let cmd = Command::new_with_args("cat", [wrapper_path]);
let output = self.cmd_output_string(cmd).await.ok()?;
// Look for the pattern: exec ... '/path/to/binary' or exec '/path/to/binary'
// The binary path is typically in single quotes in the else branch
for line in output.lines() {
let trimmed = line.trim();
// Look for lines with exec that contain a quoted path
if trimmed.starts_with("exec") {
// Reuse the shared quoted string extraction logic from desktop_file module
if let Some(path) = extract_quoted_string(trimmed, '\'') {
// Validate it looks like an absolute path to the actual binary
// (not a distrobox wrapper command)
if path.starts_with('/') && !path.contains("distrobox") {
return Some(path);
}
}
}
}
None
}
pub fn launch_app(
&self,
container: &str,
app: &ExportableApp,
) -> Result<Box<dyn Child + Send>, Error> {
let mut cmd = self.dbcmd();
cmd.arg("enter").arg("--name").arg(container).arg("--");
let to_be_replaced = [" %f", " %u", " %F", " %U"];
let cleaned_exec = to_be_replaced
.into_iter()
.fold(app.entry.exec.clone(), |acc, x| acc.replace(x, ""));
cmd.arg(cleaned_exec);
self.cmd_spawn(cmd)
}
pub async fn export_app(
&self,
container: &str,
desktop_file_path: &str,
) -> Result<String, Error> {
let mut cmd = self.dbcmd();
cmd.args(["enter", "--name", container]).extend(
"--",
&Command::new_with_args("distrobox-export", ["--app", desktop_file_path]),
);
self.cmd_output_string(cmd).await
}
pub async fn unexport_app(
&self,
container: &str,
desktop_file_path: &str,
) -> Result<String, Error> {
let mut cmd = self.dbcmd();
cmd.args(["enter", "--name", container]).extend(
"--",
&Command::new_with_args("distrobox-export", ["-d", "--app", desktop_file_path]),
);
self.cmd_output_string(cmd).await
}
pub async fn export_binary(
&self,
container: &str,
binary_name_or_path: &str,
) -> Result<String, Error> {
// Check if the input is a path or just a binary name
// If it doesn't contain a '/' it's likely just a binary name
let resolved_path = if !binary_name_or_path.contains('/') {
// Resolve the binary name to its full path using 'which'
self.resolve_binary_path(container, binary_name_or_path)
.await?
} else {
binary_name_or_path.to_string()
};
let mut cmd = self.dbcmd();
cmd.args(["enter", "--name", container]).extend(
"--",
&Command::new_with_args("distrobox-export", ["--bin", &resolved_path]),
);
self.cmd_output_string(cmd).await
}
/// Resolves a binary name to its full path using 'which' inside the container
async fn resolve_binary_path(
&self,
container: &str,
binary_name: &str,
) -> Result<String, Error> {
let mut cmd = self.dbcmd();
cmd.args(["enter", "--name", container, "--", "which", binary_name]);
let output = self.cmd_output_string(cmd).await?;
let path = output.trim();
if path.is_empty() {
return Err(Error::CommandFailed {
exit_code: Some(1),
command: format!("which {}", binary_name),
stderr: format!("Binary '{}' not found in container", binary_name),
});
}
Ok(path.to_string())
}
pub async fn unexport_binary(
&self,
container: &str,