use std::ffi::OsStr;
use std::fs;
use std::io::{self, Read, Write};
use std::path::Path;
use anyhow::{Context, Result, bail};
use clap::ValueEnum;
use clap::builder::{EnumValueParser, PossibleValue, TypedValueParser};
use clap::error::ErrorKind;
use duet_core::{EndRule, Song};
use duet_drums::DrumGrid;
use duet_midi::Midi;
use duet_schemas::{AnyDocument, Document, From, Tool};
#[derive(Clone, Copy, PartialEq, Eq, Debug, ValueEnum)]
pub enum Format {
Duet,
Midi,
Abc,
}
#[derive(Clone)]
pub struct FormatParser;
impl TypedValueParser for FormatParser {
type Value = Format;
fn parse_ref(
&self,
cmd: &clap::Command,
arg: Option<&clap::Arg>,
value: &OsStr,
) -> std::result::Result<Format, clap::Error> {
let given = value.to_string_lossy();
if matches!(
given.to_ascii_lowercase().as_str(),
"text" | "drums" | "notes" | "notefmt" | "grid"
) {
let flag = arg.map_or_else(
|| "--from or --to".to_owned(),
|a| format!("--{}", a.get_long().unwrap_or(a.get_id().as_str())),
);
return Err(clap::Error::raw(
ErrorKind::InvalidValue,
format!(
"{flag} {given} was removed: a song's or a drum grid's text is a view of a \
document. Write one with `duet view <doc.duet> --as notes|grid`, and read \
one with `duet apply <view> -o <new.duet>` (or --onto the document it came \
from)\n"
),
)
.with_cmd(cmd));
}
EnumValueParser::<Format>::new().parse_ref(cmd, arg, value)
}
fn possible_values(&self) -> Option<Box<dyn Iterator<Item = PossibleValue> + '_>> {
Some(Box::new(
Format::value_variants()
.iter()
.filter_map(ValueEnum::to_possible_value),
))
}
}
enum Named {
Song(Format),
Stream,
Cut,
View,
Unknown,
}
fn named(path: &Path) -> Named {
let name = path
.file_name()
.and_then(|n| n.to_str())
.map(str::to_ascii_lowercase)
.unwrap_or_default();
if name.ends_with(".duet.jsonl") {
return Named::Stream;
}
match name.rsplit_once('.').map(|(_, ext)| ext) {
Some("duet") => Named::Song(Format::Duet),
Some("mid" | "midi" | "smf") => Named::Song(Format::Midi),
Some("abc") => Named::Song(Format::Abc),
Some("json" | "toml") => Named::Cut,
Some("notes" | "txt" | "drums") => Named::View,
_ => Named::Unknown,
}
}
fn to_apply(path: &Path) -> String {
format!(
"A view's text is read only by `duet apply {} -o <new.duet>` (or --onto the document \
it came from), and written only by `duet view`",
path.display()
)
}
fn refusal(path: &Path, named: &Named, what: &str) -> String {
let shown = path.display();
match named {
Named::Stream => format!("{shown} is a stream (.duet.jsonl), and {what} a song"),
Named::Cut => format!(
"{shown} is not a duet document: duet's documents are .duet, and .json and .toml \
are no longer read or written"
),
Named::View => format!(
"{shown} is not a duet document or an outside format: duet reads .duet, .mid and \
.abc by name. {}",
to_apply(path)
),
Named::Song(_) | Named::Unknown => format!(
"{shown}: duet reads and writes .duet, .mid (.midi, .smf) and .abc by name; name \
any other with --from or --to (duet, midi or abc). {}",
to_apply(path)
),
}
}
pub fn song_format(path: &Path, given: Option<Format>, what: &str) -> Result<Format> {
if let Some(format) = given {
return Ok(format);
}
if path == Path::new("-") {
return Ok(Format::Duet);
}
match named(path) {
Named::Song(format) => Ok(format),
other => bail!("{}", refusal(path, &other, what)),
}
}
pub fn grid_path(path: &Path, what: &str) -> Result<()> {
if path == Path::new("-") {
return Ok(());
}
let shown = path.display();
match named(path) {
Named::Song(Format::Duet) => Ok(()),
Named::Song(format) => bail!(
"{shown} is a song's name ({}), and {what} a drum grid, a drum-grid document \
(.duet)",
format
.to_possible_value()
.map_or_else(String::new, |v| v.get_name().to_owned())
),
Named::View | Named::Unknown => bail!(
"{shown}: {what} a drum grid as a drum-grid document (.duet). {}",
to_apply(path)
),
other => bail!(
"{}",
refusal(path, &other, what).replace(" a song", " a drum grid")
),
}
}
pub fn read_grid_document(path: &Path, what: &str) -> Result<DrumGrid> {
grid_path(path, what)?;
let bytes = bytes_of(path)?;
if path == Path::new("-") && !is_document(&bytes) {
bail!("{}", not_a_document(what));
}
let text = String::from_utf8(bytes).context("a document is UTF-8 text")?;
match AnyDocument::read(&text).with_context(|| path.display().to_string())? {
AnyDocument::DrumGrid(doc) => {
let mut grid = doc.body;
grid.normalize()?;
Ok(grid)
}
other => bail!(
"{} is a {} document, and {what} a drum grid",
path.display(),
other.kind()
),
}
}
fn not_a_document(what: &str) -> String {
format!(
"standard input is not a duet document (one starts with {{), and {what} one; if it is \
a view's text, read it with `duet apply - -o -` and pipe that in, and name an ABC tune \
with --from abc"
)
}
pub fn grid_document(grid: &DrumGrid) -> Result<String> {
Ok(Document::new(tool(), grid.clone()).write()?)
}
fn bytes_of(path: &Path) -> Result<Vec<u8>> {
if path == Path::new("-") {
let mut buf = Vec::new();
io::stdin()
.read_to_end(&mut buf)
.context("reading standard input")?;
Ok(buf)
} else {
fs::read(path).with_context(|| path.display().to_string())
}
}
fn is_document(bytes: &[u8]) -> bool {
bytes.iter().find(|b| !b.is_ascii_whitespace()) == Some(&b'{')
}
pub enum Loaded {
Song(Song, Option<From>),
Grid(DrumGrid),
}
pub fn read(path: &Path, format: Format, what: &str) -> Result<Song> {
read_with_from(path, format, what).map(|(song, _)| song)
}
pub fn read_with_from(path: &Path, format: Format, what: &str) -> Result<(Song, Option<From>)> {
match read_any(path, format, what)? {
Loaded::Song(song, from) => Ok((song, from)),
Loaded::Grid(_) => bail!(
"{} is a drum-grid document, and {what} a song; duet drums render makes a song of \
one",
path.display()
),
}
}
pub fn read_any(path: &Path, format: Format, what: &str) -> Result<Loaded> {
let bytes = bytes_of(path)?;
let format = if path != Path::new("-") {
format
} else if is_document(&bytes) {
Format::Duet
} else if format == Format::Abc {
Format::Abc
} else if bytes.starts_with(b"MThd") {
Format::Midi
} else {
bail!("{}", not_a_document(what));
};
let text = || String::from_utf8(bytes.clone()).context("input is not UTF-8 text");
let (song, from) = match format {
Format::Duet => {
let doc = AnyDocument::read(&text()?).with_context(|| path.display().to_string())?;
match doc {
AnyDocument::Song(doc) => (normalized(doc.body)?, doc.from),
AnyDocument::DrumGrid(doc) => {
let mut grid = doc.body;
grid.normalize()?;
return Ok(Loaded::Grid(grid));
}
other => bail!(
"{} is a {} document, and {what} a song",
path.display(),
other.kind()
),
}
}
Format::Midi => (Song::from_midi(&bytes)?, Some(From::new("midi"))),
Format::Abc => {
let book = duet_abc::Book::parse(&text()?)?;
if book.tunes().len() > 1 {
bail!(
"{} holds {} tunes; pick one with duet abc render --tune <X>",
path.display(),
book.tunes().len()
);
}
let (song, from) = crate::abc::reading(&book.tunes()[0])?;
(song, Some(from))
}
};
Ok(Loaded::Song(song, from))
}
fn normalized(mut song: Song) -> duet_core::Result<Song> {
song.normalize()?;
Ok(song)
}
pub fn with_end(song: &Song, end: EndRule) -> Result<Song> {
let mut song = song.clone();
if song.end.is_none() {
song.end = Some(song.default_end_by(end)?);
}
Ok(song)
}
pub fn tool() -> Tool {
Tool::new("duet", env!("CARGO_PKG_VERSION"))
}
pub fn write(song: &Song, path: &Path, format: Format, end: EndRule) -> Result<()> {
write_from(song, path, format, end, None)
}
pub fn write_from(
song: &Song,
path: &Path,
format: Format,
end: EndRule,
from: Option<&From>,
) -> Result<()> {
let song = with_end(song, end)?;
let bytes = match format {
Format::Duet => {
let mut doc = Document::new(tool(), song);
doc.from = from.cloned();
doc.write()?.into_bytes()
}
Format::Midi => song.to_midi()?,
Format::Abc => duet_abc::write(&song, &duet_abc::WriteOptions::default())?.into_bytes(),
};
write_bytes(path, &bytes)
}
pub fn write_bytes(path: &Path, bytes: &[u8]) -> Result<()> {
if path == Path::new("-") {
io::stdout()
.write_all(bytes)
.context("writing standard output")
} else {
fs::write(path, bytes).with_context(|| path.display().to_string())
}
}
pub fn same_file(a: &Path, b: &Path) -> bool {
match (fs::canonicalize(a), fs::canonicalize(b)) {
(Ok(a), Ok(b)) => a == b,
_ => false,
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use duet_core::{Note, Position, Song, Track};
use super::{Format, grid_path, read, song_format, tool};
use duet_schemas::Document;
#[test]
fn a_song_is_named_by_dot_duet_mid_or_abc_and_nothing_else() {
let of = |name: &str| song_format(Path::new(name), None, "reads");
assert_eq!(of("song.duet").unwrap(), Format::Duet);
assert_eq!(of("Song.DUET").unwrap(), Format::Duet);
assert_eq!(of("take.mid").unwrap(), Format::Midi);
assert_eq!(of("take.smf").unwrap(), Format::Midi);
assert_eq!(of("tune.abc").unwrap(), Format::Abc);
assert_eq!(
of("-").unwrap(),
Format::Duet,
"standard streams are documents"
);
for (name, says) in [
("song.json", "no longer read"),
("song.toml", "no longer read"),
("beat.drums.json", "no longer read"),
("take.notes", "`duet apply take.notes -o <new.duet>`"),
("take.txt", "`duet apply take.txt -o <new.duet>`"),
("beat.drums", "`duet apply beat.drums -o <new.duet>`"),
("perf.duet.jsonl", "is a stream"),
("song", "name any other with --from or --to"),
] {
let err = of(name).expect_err(name).to_string();
assert!(err.contains(says), "{name}: {err}");
}
let given = song_format(Path::new("x.bin"), Some(Format::Midi), "reads");
assert_eq!(
given.unwrap(),
Format::Midi,
"--from says what a name does not"
);
}
#[test]
fn a_grid_is_a_document_by_name_and_a_view_is_refused() {
assert!(grid_path(Path::new("beat.duet"), "reads").is_ok());
assert!(grid_path(Path::new("-"), "reads").is_ok());
for (name, says) in [
("beat.drums", "`duet apply beat.drums -o <new.duet>`"),
("beat", "`duet apply beat -o <new.duet>`"),
("beat.mid", "is a song's name (midi)"),
("beat.drums.json", "no longer read"),
] {
let err = grid_path(Path::new(name), "reads")
.expect_err(name)
.to_string();
assert!(err.contains(says), "{name}: {err}");
}
}
#[test]
fn read_normalizes_a_document() {
let mut song = Song::default();
let mut track = Track::new("P", 1);
track.notes.push(Note::new(
Position::new(1, 1, 960),
"C4".parse().expect("C4 is a pitch"),
0.3334,
80,
));
song.tracks.push(track);
let dir = std::env::temp_dir().join(format!("duet-read-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("temp dir");
let path = dir.join("song.duet");
let text = Document::new(tool(), song).write().expect("written");
std::fs::write(&path, text).expect("write");
let read = read(&path, Format::Duet, "reads").expect("read");
let note = &read.tracks[0].notes[0];
assert_eq!((note.at.to_string(), note.beats), ("1.3.0".into(), 0.333));
std::fs::remove_dir_all(&dir).expect("clean up");
}
}