opencitations-client 0.1.0

An async Rust client for the OpenCitations Index and Meta REST APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! A command line front end to the OpenCitations apis.
//!
//! The shape of the tool follows the one thing OpenCitations is for: the
//! citation edge. `citations` walks it forwards, `references` walks it
//! backwards, and both can print bare DOIs so the answer pipes straight into
//! whatever asks about a work next -- `crossref works --id`, a bibliography, a
//! second call to this binary.

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 {
    /// The works that cite this one -- the direction crossref cannot answer
    Citations {
        /// The work, as a prefixed identifier, e.g. `doi:10.1016/j.marpol.2021.104855`
        #[arg(required = true, value_name = "ID")]
        ids: Vec<Identifier>,
        #[command(flatten)]
        refine: RefineOpts,
        #[command(flatten)]
        format: FormatOpts,
    },
    /// The works this one cites
    References {
        /// The work, as a prefixed identifier
        #[arg(required = true, value_name = "ID")]
        ids: Vec<Identifier>,
        #[command(flatten)]
        refine: RefineOpts,
        #[command(flatten)]
        format: FormatOpts,
    },
    /// How many works cite this one, without fetching them
    Count {
        /// The work, as a prefixed identifier
        #[arg(required = true, value_name = "ID")]
        ids: Vec<Identifier>,
        /// Count what it cites instead of what cites it
        #[arg(long)]
        references: bool,
        /// Count every citation the works in a venue have received. The ids are
        /// then ISSNs, e.g. `issn:0308-597X`
        #[arg(long, conflicts_with = "references")]
        venue: bool,
    },
    /// The bibliographic record behind an identifier, from OpenCitations Meta
    Meta {
        /// The works, as prefixed identifiers. Several go in one request
        #[arg(required = true, value_name = "ID")]
        ids: Vec<Identifier>,
        #[command(flatten)]
        format: FormatOpts,
    },
    /// One citation, by its own identifier
    Citation {
        /// The open citation identifier, e.g. `06024047477-06220256775`
        #[arg(value_name = "OCI")]
        oci: Oci,
        #[command(flatten)]
        format: FormatOpts,
    },
}

#[derive(Debug, Args)]
struct Out {
    /// output path where the results shall be stored
    #[arg(short, long, global = true)]
    output: Option<PathBuf>,
    /// if the output file already exists, append instead of overwriting it
    #[arg(short, long, global = true)]
    append: bool,
}

#[derive(Debug, Args)]
struct ClientOpts {
    /// An access token from opencitations.net/accesstoken. Optional, and
    /// raises the rate limit
    #[arg(long, global = true, env = "OPENCITATIONS_TOKEN")]
    token: Option<String>,
    /// The user agent to identify this caller by
    #[arg(long, global = true)]
    user_agent: Option<String>,
    /// Send at most this many requests a minute. Defaults to the documented
    /// 180; lower it when something else is querying from this address too
    #[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()
    }
}

/// How a listing is narrowed before OpenCitations answers it.
///
/// Worth doing there rather than here: a well cited work has thousands of
/// citations and they arrive in one unpaged response.
#[derive(Debug, Args)]
struct RefineOpts {
    /// Only citations created after this date, e.g. `--since 2023`
    #[arg(long, value_name = "DATE")]
    since: Option<String>,
    /// Only citations created before this date
    #[arg(long, value_name = "DATE")]
    until: Option<String>,
    /// Drop citations between works sharing an author
    #[arg(long)]
    no_author_self_citations: bool,
    /// Drop citations between works in the same venue
    #[arg(long)]
    no_journal_self_citations: bool,
    /// Order by the citing work's publication date, newest first
    #[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 {
    /// How to write the results
    #[arg(short, long, value_enum, default_value_t = Format::Json)]
    format: Format,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum Format {
    /// the whole record, as json
    Json,
    /// one line per result, for reading
    Text,
    /// bare DOIs, one per line, for piping into whatever asks next
    Dois,
}

/// Writes a listing in whichever shape was asked for.
fn write_citations<W: Write>(
    mut writer: W,
    citations: &[Citation],
    format: Format,
    // which end of the edge is the answer: the citing work for `citations`,
    // the cited one for `references`
    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()
                };
                // a work OpenCitations knows only by an omid has no doi to pipe
                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(())
}

/// Writes metadata records in whichever shape was asked for.
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?
                    };
                    // the id as well as the number, so several ids stay legible
                    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) => {
            // the chain, so `caused by` says what actually broke rather than
            // leaving the top-level message to carry all of it
            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::*;

    /// A bare doi is refused by the parser, before a request is spent finding
    /// out that OpenCitations holds nothing under it.
    #[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()
        );
    }
}