use clap::{Args, Parser, Subcommand, ValueEnum};
use opencitations_client::{
Citation, Field, Filter, Identifier, Metadata, Oci, OpenCitations, RateLimit, Refine, Sort,
};
use std::{fs, io::Write, path::PathBuf, process::ExitCode, time::Duration};
#[derive(Debug, Parser)]
#[command(
name = "opencitations",
about = "Look up who cites what, from the OpenCitations index.",
version
)]
struct App {
#[command(flatten)]
client: ClientOpts,
#[command(flatten)]
out: Out,
#[command(subcommand)]
command: Command,
}
#[derive(Debug, Subcommand)]
enum Command {
Citations {
#[arg(required = true, value_name = "ID")]
ids: Vec<Identifier>,
#[command(flatten)]
refine: RefineOpts,
#[command(flatten)]
format: FormatOpts,
},
References {
#[arg(required = true, value_name = "ID")]
ids: Vec<Identifier>,
#[command(flatten)]
refine: RefineOpts,
#[command(flatten)]
format: FormatOpts,
},
Count {
#[arg(required = true, value_name = "ID")]
ids: Vec<Identifier>,
#[arg(long)]
references: bool,
#[arg(long, conflicts_with = "references")]
venue: bool,
},
Meta {
#[arg(required = true, value_name = "ID")]
ids: Vec<Identifier>,
#[command(flatten)]
format: FormatOpts,
},
Citation {
#[arg(value_name = "OCI")]
oci: Oci,
#[command(flatten)]
format: FormatOpts,
},
}
#[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, env = "OPENCITATIONS_TOKEN")]
token: Option<String>,
#[arg(long, global = true)]
user_agent: Option<String>,
#[arg(long, global = true, value_name = "PER_MINUTE")]
rate: Option<u32>,
}
impl ClientOpts {
fn create_client(&self) -> opencitations_client::Result<OpenCitations> {
OpenCitations::builder()
.token(self.token.as_deref())
.user_agent(self.user_agent.as_deref())
.rate_limit(self.rate.map(|limit| RateLimit {
limit,
interval: Duration::from_secs(60),
}))
.build()
}
}
#[derive(Debug, Args)]
struct RefineOpts {
#[arg(long, value_name = "DATE")]
since: Option<String>,
#[arg(long, value_name = "DATE")]
until: Option<String>,
#[arg(long)]
no_author_self_citations: bool,
#[arg(long)]
no_journal_self_citations: bool,
#[arg(long)]
newest_first: bool,
}
impl RefineOpts {
fn into_refine(self) -> Refine {
let mut refine = Refine::new();
if let Some(since) = self.since {
refine = refine.filter(Filter::greater_than(Field::Creation, since));
}
if let Some(until) = self.until {
refine = refine.filter(Filter::less_than(Field::Creation, until));
}
if self.no_author_self_citations {
refine = refine.filter(Filter::is(Field::AuthorSelfCitation, "no"));
}
if self.no_journal_self_citations {
refine = refine.filter(Filter::is(Field::JournalSelfCitation, "no"));
}
if self.newest_first {
refine = refine.sort(Sort::descending(Field::Creation));
}
refine
}
}
#[derive(Debug, Args)]
struct FormatOpts {
#[arg(short, long, value_enum, default_value_t = Format::Json)]
format: Format,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum Format {
Json,
Text,
Dois,
}
fn write_citations<W: Write>(
mut writer: W,
citations: &[Citation],
format: Format,
citing: bool,
) -> Result<(), Box<dyn std::error::Error>> {
match format {
Format::Json => serde_json::to_writer_pretty(&mut writer, citations)?,
Format::Dois => {
for citation in citations {
let doi = if citing {
citation.citing_doi()
} else {
citation.cited_doi()
};
if let Some(doi) = doi {
writeln!(writer, "{doi}")?;
}
}
}
Format::Text => {
for citation in citations {
let other = if citing {
&citation.citing
} else {
&citation.cited
};
let doi = other
.iter()
.find_map(Identifier::as_doi)
.map(str::to_string)
.unwrap_or_else(|| other.first().map(ToString::to_string).unwrap_or_default());
let when = citation
.creation
.map(|date| date.to_string())
.unwrap_or_else(|| "date unknown".to_string());
let mut marks = Vec::new();
if citation.author_self_citation {
marks.push("author self-citation");
}
if citation.journal_self_citation {
marks.push("journal self-citation");
}
let marks = if marks.is_empty() {
String::new()
} else {
format!(" [{}]", marks.join(", "))
};
writeln!(writer, "{when} {doi}{marks}")?;
}
let plural = if citations.len() == 1 { "" } else { "s" };
writeln!(writer, "-- {} citation{plural}", citations.len())?;
}
}
Ok(())
}
fn write_metadata<W: Write>(
mut writer: W,
records: &[Metadata],
format: Format,
) -> Result<(), Box<dyn std::error::Error>> {
match format {
Format::Json => serde_json::to_writer_pretty(&mut writer, records)?,
Format::Dois => {
for record in records {
if let Some(doi) = record.doi() {
writeln!(writer, "{doi}")?;
}
}
}
Format::Text => {
for record in records {
let authors = record
.author
.iter()
.map(|author| author.name.as_str())
.collect::<Vec<_>>()
.join("; ");
writeln!(
writer,
"{}\n {}\n {}{}\n {}",
record.title.as_deref().unwrap_or("(untitled)"),
if authors.is_empty() {
"(no authors recorded)".to_string()
} else {
authors
},
record
.venue
.as_ref()
.map(|venue| venue.name.clone())
.unwrap_or_else(|| "(no venue recorded)".to_string()),
record
.published
.map(|date| format!(", {date}"))
.unwrap_or_default(),
record
.doi()
.map(|doi| format!("https://doi.org/{doi}"))
.unwrap_or_else(|| "(no doi)".to_string()),
)?;
}
}
}
Ok(())
}
impl Command {
async fn run<W: Write>(
self,
mut writer: W,
client: &OpenCitations,
) -> Result<ExitCode, Box<dyn std::error::Error>> {
match self {
Command::Citations {
ids,
refine,
format,
} => {
let refine = refine.into_refine();
let mut all = Vec::new();
for id in &ids {
all.extend(client.citations_where(id, &refine).await?);
}
write_citations(writer, &all, format.format, true)?;
}
Command::References {
ids,
refine,
format,
} => {
let refine = refine.into_refine();
let mut all = Vec::new();
for id in &ids {
all.extend(client.references_where(id, &refine).await?);
}
write_citations(writer, &all, format.format, false)?;
}
Command::Count {
ids,
references,
venue,
} => {
for id in &ids {
let count = if venue {
client.venue_citation_count(id).await?
} else if references {
client.reference_count(id).await?
} else {
client.citation_count(id).await?
};
if ids.len() == 1 {
writeln!(writer, "{count}")?;
} else {
writeln!(writer, "{count}\t{id}")?;
}
}
}
Command::Meta { ids, format } => {
let records = client.metadata(&ids).await?;
write_metadata(writer, &records, format.format)?;
}
Command::Citation { oci, format } => match client.citation(&oci).await? {
Some(citation) => write_citations(writer, &[citation], format.format, true)?,
None => {
eprintln!("opencitations: no citation `{oci}`");
return Ok(ExitCode::FAILURE);
}
},
}
Ok(ExitCode::SUCCESS)
}
}
#[tokio::main]
async fn main() -> ExitCode {
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.with_writer(std::io::stderr)
.init();
let app = App::parse();
match run(app).await {
Ok(code) => code,
Err(err) => {
eprintln!("opencitations: {err}");
let mut source = err.source();
while let Some(cause) = source {
eprintln!("caused by: {cause}");
source = cause.source();
}
ExitCode::FAILURE
}
}
}
async fn run(app: App) -> Result<ExitCode, Box<dyn std::error::Error>> {
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,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_unprefixed_identifier_is_refused_at_the_command_line() {
let parsed =
App::try_parse_from(["opencitations", "citations", "10.1016/j.marpol.2021.104855"]);
let err = parsed.unwrap_err().to_string();
assert!(err.contains("doi:10.1016/j.marpol.2021.104855"), "{err}");
}
#[test]
fn the_narrowing_flags_render_the_filters_the_api_reads() {
let App { command, .. } = App::try_parse_from([
"opencitations",
"citations",
"doi:10.1016/j.marpol.2021.104855",
"--since",
"2023",
"--no-author-self-citations",
"--newest-first",
])
.unwrap();
let Command::Citations { refine, .. } = command else {
panic!("did not parse into a citations command");
};
let params = refine.into_refine();
assert!(!params.is_empty());
}
#[test]
fn an_oci_is_parsed_before_it_is_sent() {
assert!(App::try_parse_from(["opencitations", "citation", "not-an-oci"]).is_err());
assert!(
App::try_parse_from(["opencitations", "citation", "06024047477-06220256775"]).is_ok()
);
}
}