use clap::{Args, Parser, Subcommand, ValueEnum};
use crossref_client::{
AsyncIterator, CnFormat, Crossref, FundersQuery, JournalsQuery, LicensesQuery, MembersQuery,
Order, ResultControl, Sort, Type, WorkResultControl, WorksQuery,
};
use std::{fs, io::Write, path::PathBuf};
#[derive(Debug, Parser)]
#[command(
name = "crossref",
about = "Access the crossref API from the command line.",
version
)]
struct App {
#[command(flatten)]
client: ClientOpts,
#[command(flatten)]
out: Out,
#[command(subcommand)]
command: Command,
}
#[derive(Debug, Subcommand)]
enum Command {
Works {
#[arg(short, long)]
id: Option<String>,
#[arg(short, long)]
deep_page: bool,
#[command(flatten)]
opts: WorksOpts,
#[command(subcommand)]
combined: Option<Combined>,
},
Funders {
#[arg(short, long)]
id: Option<String>,
#[command(flatten)]
opts: ListOpts,
},
Members {
#[arg(short, long)]
id: Option<String>,
#[command(flatten)]
opts: ListOpts,
},
Journals {
#[arg(short, long)]
id: Option<String>,
#[command(flatten)]
opts: ListOpts,
},
Licenses {
#[command(flatten)]
opts: ListOpts,
},
Prefixes {
#[arg(short, long)]
id: String,
},
Types {
#[arg(short, long)]
id: Option<Type>,
},
Transform {
doi: String,
#[arg(long, value_enum, default_value_t = Format::Bibtex)]
format: Format,
#[arg(long, default_value = "apa")]
style: String,
#[arg(long)]
locale: Option<String>,
},
Styles,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum Format {
RdfXml,
Turtle,
CiteprocJson,
CiteprocJsonIsh,
Ris,
Bibtex,
CrossrefXml,
CrossrefTdm,
Citation,
}
impl Format {
fn into_cn_format(self, style: String, locale: Option<String>) -> CnFormat {
match self {
Format::RdfXml => CnFormat::RdfXml,
Format::Turtle => CnFormat::Turtle,
Format::CiteprocJson => CnFormat::CiteProcJson,
Format::CiteprocJsonIsh => CnFormat::CiteProcJsonIsh,
Format::Ris => CnFormat::Ris,
Format::Bibtex => CnFormat::BibTex,
Format::CrossrefXml => CnFormat::CrossrefXml,
Format::CrossrefTdm => CnFormat::CrossrefTdm,
Format::Citation => CnFormat::Bibliography { style, locale },
}
}
}
#[derive(Debug, Subcommand)]
enum Combined {
Member { id: String },
Funder { id: String },
Journal { id: String },
Prefix { id: String },
Type { id: String },
}
#[derive(Debug, Args)]
struct Out {
#[arg(short, long, global = true)]
output: Option<PathBuf>,
#[arg(short, long, global = true)]
append: bool,
}
#[derive(Debug, Args)]
struct ClientOpts {
#[arg(long, global = true)]
user_agent: Option<String>,
#[arg(long, global = true)]
token: Option<String>,
#[arg(long, global = true)]
polite: Option<String>,
}
impl ClientOpts {
fn create_client(&self) -> crossref_client::Result<Crossref> {
Crossref::builder()
.user_agent(self.user_agent.as_deref())
.token(self.token.as_deref())
.polite(self.polite.as_deref())
.build()
}
}
#[derive(Debug, Args)]
struct ListOpts {
#[arg(short, long = "query")]
query_terms: Vec<String>,
#[arg(short, long)]
limit: Option<usize>,
#[arg(long)]
offset: Option<usize>,
}
impl ListOpts {
fn result_control(&self) -> Option<ResultControl> {
match (self.limit, self.offset) {
(Some(rows), Some(offset)) => Some(ResultControl::RowsOffset { rows, offset }),
(Some(rows), None) => Some(ResultControl::Rows(rows)),
(None, Some(offset)) => Some(ResultControl::Offset(offset)),
(None, None) => None,
}
}
}
#[derive(Debug, Args)]
struct WorksOpts {
#[command(flatten)]
list: ListOpts,
#[arg(long)]
sort: Option<Sort>,
#[arg(long)]
order: Option<Order>,
#[arg(long)]
sample: Option<usize>,
}
impl WorksOpts {
fn into_query(self) -> WorksQuery {
WorksQuery::empty()
.queries(&self.list.query_terms)
.sort(self.sort)
.order(self.order)
.sample(self.sample)
.result_control(self.list.result_control().map(WorkResultControl::Standard))
}
}
impl Command {
async fn run<W: Write>(
self,
mut writer: W,
client: &Crossref,
) -> Result<(), Box<dyn std::error::Error>> {
match self {
Command::Types { id } => match id {
Some(id) => serde_json::to_writer_pretty(writer, &client.type_(&id).await?)?,
None => serde_json::to_writer_pretty(writer, &client.types().await?)?,
},
Command::Prefixes { id } => {
serde_json::to_writer_pretty(writer, &client.prefix(&id).await?)?
}
Command::Styles => serde_json::to_writer_pretty(writer, &client.styles().await?)?,
Command::Transform {
doi,
format,
style,
locale,
} => {
let body = client
.transform(&doi, &format.into_cn_format(style, locale))
.await?;
writer.write_all(body.as_bytes())?;
}
Command::Journals { id, opts } => match id {
Some(id) => serde_json::to_writer_pretty(writer, &client.journal(&id).await?)?,
None => {
let query = JournalsQuery::empty()
.queries(&opts.query_terms)
.result_control(opts.result_control());
serde_json::to_writer_pretty(writer, &client.journals(query).await?)?
}
},
Command::Licenses { opts } => {
let query = LicensesQuery::empty()
.queries(&opts.query_terms)
.result_control(opts.result_control());
serde_json::to_writer_pretty(writer, &client.licenses(query).await?)?
}
Command::Members { id, opts } => match id {
Some(id) => serde_json::to_writer_pretty(writer, &client.member(&id).await?)?,
None => {
let query = MembersQuery::empty()
.queries(&opts.query_terms)
.result_control(opts.result_control());
serde_json::to_writer_pretty(writer, &client.members(query).await?)?
}
},
Command::Funders { id, opts } => match id {
Some(id) => serde_json::to_writer_pretty(writer, &client.funder(&id).await?)?,
None => {
let query = FundersQuery::empty()
.queries(&opts.query_terms)
.result_control(opts.result_control());
serde_json::to_writer_pretty(writer, &client.funders(query).await?)?
}
},
Command::Works {
id,
opts,
combined,
deep_page,
} => {
if let Some(id) = &id {
serde_json::to_writer_pretty(writer, &client.work(id).await?)?;
return Ok(());
}
let query = opts.into_query();
let query = match combined {
Some(Combined::Journal { id }) => {
query.into_combined_query::<crossref_client::Journals>(&id)
}
Some(Combined::Type { id }) => {
query.into_combined_query::<crossref_client::Types>(&id)
}
Some(Combined::Funder { id }) => {
query.into_combined_query::<crossref_client::Funders>(&id)
}
Some(Combined::Member { id }) => {
query.into_combined_query::<crossref_client::Members>(&id)
}
Some(Combined::Prefix { id }) => {
query.into_combined_query::<crossref_client::Prefixes>(&id)
}
None => query.into(),
};
if deep_page {
let mut pages = client.deep_page(query);
let mut works = Vec::new();
while let Some(page) = pages.next().await {
works.extend(page?.items);
}
serde_json::to_writer_pretty(writer, &works)?
} else {
serde_json::to_writer_pretty(writer, &client.works(query).await?)?
}
}
}
Ok(())
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init();
let app = App::parse();
let client = app.client.create_client()?;
match &app.out.output {
Some(path) => {
let file = if app.out.append && path.exists() {
fs::OpenOptions::new().append(true).open(path)?
} else {
fs::File::create(path)?
};
app.command.run(file, &client).await?;
}
None => app.command.run(std::io::stdout(), &client).await?,
}
Ok(())
}