#![forbid(unsafe_code)]
mod abc;
mod capture;
mod config;
mod drums;
mod io;
mod play;
mod record;
mod song;
mod view;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use anyhow::{Result, bail};
use clap::{Parser, Subcommand};
use duet_core::Grid;
use crate::abc::AbcCommand;
use crate::capture::CaptureCommand;
use crate::config::{Config, Dirs};
use crate::drums::{DrumsCommand, ReadOptions};
use crate::io::{Format, FormatParser, Loaded, read_any, song_format, write_from};
use crate::song::SongCommand;
#[derive(Parser)]
#[command(name = "duet", version, about)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
Convert {
input: PathBuf,
output: PathBuf,
#[arg(long, value_parser = FormatParser)]
from: Option<Format>,
#[arg(long, value_parser = FormatParser)]
to: Option<Format>,
#[arg(long)]
grid: Option<Grid>,
#[arg(long)]
track: Option<String>,
#[arg(long)]
bars: Option<u32>,
#[arg(long)]
snap_levels: bool,
},
View(view::ViewArgs),
Apply(view::ApplyArgs),
#[command(subcommand)]
Song(SongCommand),
#[command(subcommand)]
Drums(DrumsCommand),
#[command(subcommand)]
Abc(AbcCommand),
#[command(subcommand)]
Capture(CaptureCommand),
Play(play::PlayArgs),
Record(record::RecordArgs),
#[command(subcommand)]
Config(ConfigCommand),
}
#[derive(Subcommand)]
enum ConfigCommand {
Path,
Show,
}
fn run(cli: Cli, dirs: &Dirs) -> Result<()> {
match cli.command {
Command::Convert {
input,
output,
from,
to,
grid,
track,
bars,
snap_levels,
} => convert(
&input,
&output,
from,
to,
GridFlags {
grid,
track,
bars,
snap_levels,
},
&Config::load(dirs)?,
),
Command::Song(command) => song::run(command, &Config::load(dirs)?),
Command::Drums(command) => drums::run(command, &Config::load(dirs)?),
Command::Abc(command) => abc::run(command, &Config::load(dirs)?),
Command::Capture(command) => capture::run(command, &Config::load(dirs)?),
Command::Play(args) => play::run(args, &Config::load(dirs)?),
Command::Record(args) => record::run(args),
Command::View(args) => view::run_view(args, &Config::load(dirs)?),
Command::Apply(args) => view::run_apply(args, &Config::load(dirs)?),
Command::Config(ConfigCommand::Path) => stdout(&config::describe_paths(dirs)),
Command::Config(ConfigCommand::Show) => stdout(&Config::load(dirs)?.show()),
}
}
struct GridFlags {
grid: Option<Grid>,
track: Option<String>,
bars: Option<u32>,
snap_levels: bool,
}
fn convert(
input: &Path,
output: &Path,
from: Option<Format>,
to: Option<Format>,
flags: GridFlags,
config: &Config,
) -> Result<()> {
let GridFlags {
grid,
track,
bars,
snap_levels,
} = flags;
let any_grid_flag = grid.is_some() || track.is_some() || bars.is_some() || snap_levels;
let format = song_format(input, from, "convert reads")?;
let read = read_any(input, format, "convert reads")?;
let to = song_format(output, to, "convert writes")?;
let to_grid = to == Format::Duet && (matches!(read, Loaded::Grid(_)) || any_grid_flag);
if let (Loaded::Grid(source), true, None) = (&read, to_grid, grid) {
let given: Vec<&str> = [(track.is_some(), "--track"), (bars.is_some(), "--bars")]
.into_iter()
.filter_map(|(set, flag)| set.then_some(flag))
.collect();
if !given.is_empty() {
bail!(
"{} {} for reading a song's drum track, and need --grid; without it, a grid \
is copied as it is",
given.join(", "),
if given.len() == 1 { "is" } else { "are" },
);
}
let copy = if snap_levels {
source.snapped_to_levels()
} else {
source.clone()
};
return drums::write_grid(©, output, "convert writes");
}
let (song, from) = match read {
Loaded::Song(song, from) => (song, from),
Loaded::Grid(grid) => (grid.to_song()?, None),
};
if !to_grid {
if any_grid_flag {
let given: Vec<&str> = [
(grid.is_some(), "--grid"),
(track.is_some(), "--track"),
(bars.is_some(), "--bars"),
(snap_levels, "--snap-levels"),
]
.into_iter()
.filter_map(|(set, flag)| set.then_some(flag))
.collect();
bail!(
"{} {} for writing a drum grid, and {} is not one; a grid is written as a \
drum-grid document (.duet), and `duet view --as grid` shows a song's drum track \
as a grid's text",
given.join(", "),
if given.len() == 1 { "is" } else { "are" },
output.display()
);
}
return write_from(&song, output, to, config.end, from.as_ref());
}
let Some(grid) = grid else {
bail!(
"writing a drum grid from a song needs --grid, the step, such as --grid 1/16; duet \
never guesses it"
);
};
let options = ReadOptions {
grid,
track,
bars,
snap_levels,
};
drums::write_grid(
&drums::grid_of_song(&song, &options, config)?,
output,
"convert writes",
)
}
fn stdout(text: &str) -> Result<()> {
use std::io::Write as _;
std::io::stdout()
.write_all(text.as_bytes())
.map_err(|e| anyhow::anyhow!("writing standard output: {e}"))
}
fn main() -> ExitCode {
match Dirs::find().and_then(|dirs| run(Cli::parse(), &dirs)) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("duet: {e:#}");
ExitCode::FAILURE
}
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use clap::Parser;
use crate::config::Dirs;
use crate::{Cli, run};
pub(crate) fn run_hermetic(args: &[&str]) -> anyhow::Result<()> {
static N: AtomicUsize = AtomicUsize::new(0);
let user = std::env::temp_dir().join(format!(
"duet-no-config-{}-{}",
std::process::id(),
N.fetch_add(1, Ordering::Relaxed)
));
let dirs = Dirs {
user: Some((user, "the test's empty config directory")),
project: None,
};
run(
Cli::parse_from(std::iter::once("duet").chain(args.iter().copied())),
&dirs,
)
}
}