Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: selection dialog when running pixi run without arguments #1649

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions crates/pixi_manifest/src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ impl From<TaskName> for String {
task_name.0 // Assuming TaskName is a tuple struct with the first element as String
}
}

/// Represents different types of scripts
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
Expand Down Expand Up @@ -140,7 +139,7 @@ impl Task {
Task::Plain(_) => None,
Task::Custom(_) => None,
Task::Execute(exe) => exe.description.as_deref(),
Task::Alias(_) => None,
Task::Alias(alias) => alias.description.as_deref(),
}
}

Expand Down
72 changes: 66 additions & 6 deletions src/cli/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,10 @@ use tracing::Level;

/// Runs task in project.
#[derive(Parser, Debug, Default)]
#[clap(trailing_var_arg = true, arg_required_else_help = true)]
#[clap(trailing_var_arg = true)]
pub struct Args {
/// The pixi task or a task shell command you want to run in the project's environment, which can be an executable in the environment's PATH.
#[arg(required = true)]
pub task: Vec<String>,
pub task: Option<Vec<String>>,

/// The path to 'pixi.toml' or 'pyproject.toml'
#[arg(long)]
Expand Down Expand Up @@ -100,7 +99,11 @@ pub async fn execute(args: Args) -> miette::Result<()> {
)
.with_disambiguate_fn(disambiguate_task_interactive);

let task_graph = TaskGraph::from_cmd_args(&project, &search_environment, args.task)?;
let task_graph = TaskGraph::from_cmd_args(
&project,
&search_environment,
determine_task(&args.task, &project)?,
)?;

tracing::info!("Task graph: {}", task_graph);

Expand Down Expand Up @@ -210,13 +213,13 @@ pub async fn execute(args: Args) -> miette::Result<()> {
fn command_not_found<'p>(project: &'p Project, explicit_environment: Option<Environment<'p>>) {
let available_tasks: HashSet<TaskName> =
if let Some(explicit_environment) = explicit_environment {
explicit_environment.get_filtered_tasks()
explicit_environment.get_filtered_task_names()
} else {
project
.environments()
.into_iter()
.filter(|env| verify_current_platform_has_required_virtual_packages(env).is_ok())
.flat_map(|env| env.get_filtered_tasks())
.flat_map(|env| env.get_filtered_task_names())
.collect()
};

Expand Down Expand Up @@ -344,3 +347,60 @@ fn disambiguate_task_interactive<'p>(
.map_or(None, identity)
.map(|idx| problem.environments[idx].clone())
}

/// Function to determine the task to run, spawn a dialog if no task is provided.
fn determine_task(task: &Option<Vec<String>>, project: &Project) -> miette::Result<Vec<String>> {
if let Some(task) = task {
Ok(task.clone())
} else {
let theme = ColorfulTheme {
active_item_style: console::Style::new().for_stderr().magenta(),
..ColorfulTheme::default()
};
let runnable_tasks: Vec<(TaskName, String)> = project
.environments()
.into_iter()
.filter(|env| verify_current_platform_has_required_virtual_packages(env).is_ok())
.flat_map(|env| env.get_filtered_tasks())
.map(|(task_name, task)| (task_name, task.description().unwrap_or("").to_string()))
.unique()
.sorted()
.collect_vec();

// Get the longest task name for padding if there is any description
let width = if runnable_tasks.iter().any(|(_, desc)| !desc.is_empty()) {
runnable_tasks
.iter()
.map(|(name, _)| name.fancy_display().to_string().len())
.max()
.unwrap_or(0)
+ 2
} else {
0
};

// Format the items
let formatted_items = runnable_tasks
.iter()
.map(|(name, desc)| {
format!(
"{:<width$}{}",
name.fancy_display().to_string(),
desc,
width = width
)
})
.collect::<Vec<String>>();

dialoguer::Select::with_theme(&theme)
.with_prompt("Please select a task to run:")
.items(&formatted_items)
.default(0)
.interact_opt()
.map(|idx_opt| match idx_opt {
Some(idx) => Ok(vec![runnable_tasks[idx].clone().0.to_string()]),
None => Err(miette::miette!("Task selection cancelled by user.")),
})
.into_diagnostic()?
}
}
4 changes: 2 additions & 2 deletions src/cli/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,15 +399,15 @@ pub fn execute(args: Args) -> miette::Result<()> {
.transpose()?;
let available_tasks: HashSet<TaskName> =
if let Some(explicit_environment) = explicit_environment {
explicit_environment.get_filtered_tasks()
explicit_environment.get_filtered_task_names()
} else {
project
.environments()
.into_iter()
.filter(|env| {
verify_current_platform_has_required_virtual_packages(env).is_ok()
})
.flat_map(|env| env.get_filtered_tasks())
.flat_map(|env| env.get_filtered_task_names())
.collect()
};

Expand Down
23 changes: 21 additions & 2 deletions src/project/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@

/// Return all tasks available for the given environment
/// This will not return task prefixed with _
pub fn get_filtered_tasks(&self) -> HashSet<TaskName> {
pub fn get_filtered_task_names(&self) -> HashSet<TaskName> {
self.tasks(Some(self.best_platform()))
.into_iter()
.flat_map(|tasks| {
Expand All @@ -183,6 +183,25 @@
.map(ToOwned::to_owned)
.collect()
}

/// Return all tasks available for the given environment
/// This will not return task prefixed with _
pub fn get_filtered_tasks(&self) -> HashMap<TaskName, Task> {
self.tasks(Some(self.best_platform()))
.into_iter()
.flat_map(|tasks| {
tasks.into_iter().filter_map(|(key, value)| {
if !key.as_str().starts_with('_') {
Some((key, value))
} else {
None
}
})
})
.map(|(key, value)| (key.to_owned(), value.clone()))

Check warning on line 201 in src/project/environment.rs

View workflow job for this annotation

GitHub Actions / Cargo Format

Diff in /home/runner/work/pixi/pixi/src/project/environment.rs
.collect()
}

/// Returns the task with the given `name` and for the specified `platform`
/// or an `UnknownTask` which explains why the task was not available.
pub fn task(
Expand Down Expand Up @@ -415,7 +434,7 @@
)
.unwrap();

let task = manifest.default_environment().get_filtered_tasks();
let task = manifest.default_environment().get_filtered_task_names();

assert_eq!(task.len(), 1);
assert!(task.contains(&"foo".into()));
Expand Down
9 changes: 7 additions & 2 deletions tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,8 +323,13 @@ impl PixiControl {
.map(|e| e.best_platform())
.or(Some(Platform::current())),
);
let task_graph = TaskGraph::from_cmd_args(&project, &search_env, args.task)
.map_err(RunError::TaskGraphError)?;
let task_graph = TaskGraph::from_cmd_args(
&project,
&search_env,
args.task
.expect("expected a task, as tests don't run the dialog"),
)
.map_err(RunError::TaskGraphError)?;

// Iterate over all tasks in the graph and execute them.
let mut task_env = None;
Expand Down
6 changes: 3 additions & 3 deletions tests/install_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ async fn install_run_python() {
// Check if python is installed and can be run
let result = pixi
.run(run::Args {
task: string_from_iter(["python", "--version"]),
task: Some(string_from_iter(["python", "--version"])),
..Default::default()
})
.await
Expand Down Expand Up @@ -229,7 +229,7 @@ async fn install_locked_with_config() {

let result = pixi
.run(Args {
task: vec!["which_python".to_string()],
task: Some(vec!["which_python".to_string()]),
manifest_path: None,
..Default::default()
})
Expand Down Expand Up @@ -277,7 +277,7 @@ async fn install_frozen() {
frozen: true,
..Default::default()
},
task: string_from_iter(["python", "--version"]),
task: Some(string_from_iter(["python", "--version"])),
..Default::default()
})
.await
Expand Down
12 changes: 6 additions & 6 deletions tests/task_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ async fn test_alias() {

let result = pixi
.run(Args {
task: vec!["helloworld".to_string()],
task: Some(vec!["helloworld".to_string()]),
manifest_path: None,
..Default::default()
})
Expand Down Expand Up @@ -184,7 +184,7 @@ async fn test_cwd() {

let result = pixi
.run(Args {
task: vec!["pwd-test".to_string()],
task: Some(vec!["pwd-test".to_string()]),
manifest_path: None,
..Default::default()
})
Expand All @@ -204,7 +204,7 @@ async fn test_cwd() {

assert!(pixi
.run(Args {
task: vec!["unknown-cwd".to_string()],
task: Some(vec!["unknown-cwd".to_string()]),
manifest_path: None,
..Default::default()
})
Expand All @@ -229,7 +229,7 @@ async fn test_task_with_env() {

let result = pixi
.run(Args {
task: vec!["env-test".to_string()],
task: Some(vec!["env-test".to_string()]),
manifest_path: None,
..Default::default()
})
Expand All @@ -253,7 +253,7 @@ async fn test_clean_env() {
.unwrap();

let run = pixi.run(Args {
task: vec!["env-test".to_string()],
task: Some(vec!["env-test".to_string()]),
manifest_path: None,
clean_env: true,
..Default::default()
Expand All @@ -270,7 +270,7 @@ async fn test_clean_env() {

let result = pixi
.run(Args {
task: vec!["env-test".to_string()],
task: Some(vec!["env-test".to_string()]),
manifest_path: None,
clean_env: false,
..Default::default()
Expand Down
Loading