/
lib.rs
483 lines (415 loc) · 15.2 KB
/
lib.rs
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
use std::{path::Path, sync::Arc};
use provider::{
codecs,
common::{
eyre::{bail, eyre, Result},
once_cell::sync::Lazy,
serde_json,
tokio::sync::mpsc,
},
http_utils::http::{Request, Response},
stencila_schema::Node,
EnrichOptions, ProviderTrait,
};
pub use provider::{DetectItem, ExportOptions, ImportOptions, Provider, SyncOptions, WatchMode};
// Re-exports for consumers of this crate
pub use ::provider;
// The following high level functions hide the implementation
// detail of having a static list of providers. They are intended as the
// only public interface for this crate.
pub async fn detect(node: &Node) -> Result<Vec<DetectItem>> {
PROVIDERS.detect(node).await
}
pub async fn resolve(identifier: &str) -> Result<(String, Node)> {
let root = Node::String(identifier.to_string());
let detections = detect(&root).await?;
match detections.first() {
Some(detection) => Ok((detection.provider.clone(), detection.node.clone())),
None => bail!("Unable to resolve identifier `{}`", identifier),
}
}
pub async fn enrich(node: Node, options: Option<EnrichOptions>) -> Result<Node> {
PROVIDERS.enrich(node, options).await
}
pub async fn import(node: &Node, path: &Path, options: Option<ImportOptions>) -> Result<()> {
PROVIDERS.import(node, path, options).await
}
pub async fn export(node: &Node, path: &Path, options: Option<ExportOptions>) -> Result<()> {
PROVIDERS.export(node, path, options).await
}
pub async fn sync(
node: &Node,
dest: &Path,
request: &Request<serde_json::Value>,
options: Option<SyncOptions>,
) -> Result<Response<String>> {
PROVIDERS.sync(node, dest, request, options).await
}
pub async fn cron(
node: &Node,
dest: &Path,
action: &str,
schedule: &str,
canceller: mpsc::Receiver<()>,
) -> Result<()> {
PROVIDERS
.cron(node, dest, action, schedule, canceller)
.await
}
/// The set of registered providers in the current process
static PROVIDERS: Lazy<Arc<Providers>> = Lazy::new(|| Arc::new(Providers::new()));
/// A set of registered providers, either built-in, or provided by plugins
struct Providers {
inner: Vec<Provider>,
}
/// A macro to dispatch methods to builtin providers
macro_rules! dispatch_builtins {
($var:expr, $method:ident $(,$arg:expr)*) => {
match $var.as_str() {
#[cfg(feature = "provider-doi")]
"doi" => provider_doi::DoiProvider::$method($($arg),*),
#[cfg(feature = "provider-elife")]
"elife" => provider_elife::ElifeProvider::$method($($arg),*),
#[cfg(feature = "provider-gdrive")]
"gdrive" => provider_gdrive::GoogleDriveProvider::$method($($arg),*),
#[cfg(feature = "provider-github")]
"github" => provider_github::GithubProvider::$method($($arg),*),
#[cfg(feature = "provider-gitlab")]
"gitlab" => provider_gitlab::GitlabProvider::$method($($arg),*),
#[cfg(feature = "provider-http")]
"http" => provider_http::HttpProvider::$method($($arg),*),
_ => bail!("Unable to dispatch to provider `{}`", $var)
}
};
}
impl Providers {
/// Create a set of providers
///
/// Ordering is important because detection is done in order and often
/// when there are multiple detections for the same location (e.g. a GitHub
/// url and a generic HTTP/S url) the first is used.
pub fn new() -> Self {
let inner = vec![
#[cfg(feature = "provider-doi")]
provider_doi::DoiProvider::spec(),
#[cfg(feature = "provider-elife")]
provider_elife::ElifeProvider::spec(),
#[cfg(feature = "provider-gdrive")]
provider_gdrive::GoogleDriveProvider::spec(),
#[cfg(feature = "provider-github")]
provider_github::GithubProvider::spec(),
#[cfg(feature = "provider-gitlab")]
provider_gitlab::GitlabProvider::spec(),
#[cfg(feature = "provider-http")]
provider_http::HttpProvider::spec(),
];
Self { inner }
}
/// List the available providers
fn list(&self) -> Vec<String> {
self.inner
.iter()
.map(|provider| provider.name.clone())
.collect()
}
/// Get a provider by name
fn get(&self, name: &str) -> Result<Provider> {
for provider in &self.inner {
if provider.name == name {
return Ok(provider.clone());
}
}
bail!("No provider with name `{}`", name)
}
/// Find the provider which recognizes a node
fn provider_for(&self, node: &Node) -> Result<Provider> {
for provider in &self.inner {
if dispatch_builtins!(provider.name, recognize, node) {
return Ok(provider.clone());
}
}
bail!("None of the registered providers recognize this node")
}
/// Detect nodes within a node
///
/// The `detect` method of each provider is called on the node and the result
/// is a list of detections across all providers.
async fn detect(&self, node: &Node) -> Result<Vec<DetectItem>> {
let mut detected = Vec::new();
for provider in &self.inner {
let mut result = dispatch_builtins!(provider.name, detect, node).await?;
detected.append(&mut result);
}
Ok(detected)
}
/// Enrich a node
///
/// The `enrich` method of each provider is called on the node possibly mutating it with new
/// and/or different values for fields.
async fn enrich(&self, mut node: Node, options: Option<EnrichOptions>) -> Result<Node> {
for provider in &self.inner {
node = dispatch_builtins!(provider.name, enrich, node, options.clone()).await?;
}
Ok(node)
}
/// Import content from a remote [`Node`] to a local path
async fn import(&self, node: &Node, path: &Path, options: Option<ImportOptions>) -> Result<()> {
let provider = self.provider_for(node)?;
dispatch_builtins!(provider.name, import, node, path, options.clone()).await
}
/// Export content from a local path to a remote [`Node`]
async fn export(&self, node: &Node, path: &Path, options: Option<ExportOptions>) -> Result<()> {
let provider = self.provider_for(node)?;
dispatch_builtins!(provider.name, export, node, path, options.clone()).await
}
/// Synchronize changes between a remote [`Node`] and a local path
async fn sync(
&self,
node: &Node,
path: &Path,
request: &Request<serde_json::Value>,
options: Option<SyncOptions>,
) -> Result<Response<String>> {
let resolved = match node {
Node::String(identifier) => resolve(identifier).await?.1,
_ => node.to_owned(),
};
let provider = self.provider_for(&resolved)?;
dispatch_builtins!(provider.name, sync, &resolved, path, request, options).await
}
/// Schedule import and/or export to/from a remove [`Node`] and a local path
async fn cron(
&self,
node: &Node,
path: &Path,
action: &str,
schedule: &str,
canceller: mpsc::Receiver<()>,
) -> Result<()> {
let provider = self.provider_for(node)?;
dispatch_builtins!(provider.name, cron, node, path, action, schedule, canceller).await
}
}
impl Default for Providers {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "cli")]
#[allow(deprecated)] // Remove when using clap 4.0 (https://github.com/clap-rs/clap/issues/3822)
pub mod commands {
use std::path::PathBuf;
use cli_utils::{
clap::{self, Parser},
common::async_trait::async_trait,
result, Result, Run,
};
use super::*;
/// Manage and use source providers
#[derive(Debug, Parser)]
pub struct Command {
#[clap(subcommand)]
pub action: Action,
}
#[derive(Debug, Parser)]
pub enum Action {
List(List),
Show(Show),
Detect(Detect),
Enrich(Enrich),
Import(Import),
Export(Export),
Cron(Cron),
}
#[async_trait]
impl Run for Command {
async fn run(&self) -> Result {
match &self.action {
Action::List(action) => action.run().await,
Action::Show(action) => action.run().await,
Action::Detect(action) => action.run().await,
Action::Enrich(action) => action.run().await,
Action::Import(action) => action.run().await,
Action::Export(action) => action.run().await,
Action::Cron(action) => action.run().await,
}
}
}
/// List the providers that are available
///
/// The list of available providers includes those that are built into the Stencila
/// binary as well as those provided by plugins.
#[derive(Debug, Parser)]
pub struct List {}
#[async_trait]
impl Run for List {
async fn run(&self) -> Result {
let list = PROVIDERS.list();
result::value(list)
}
}
/// Show the specifications of a provider
#[derive(Debug, Parser)]
pub struct Show {
/// The name of the provider
///
/// To get the list of provider names using `stencila providers list`.
name: String,
}
#[async_trait]
impl Run for Show {
async fn run(&self) -> Result {
let provider = PROVIDERS.get(&self.name)?;
result::value(provider)
}
}
/// Detect nodes within a file or string
#[derive(Debug, Parser)]
pub struct Detect {
/// The path to the file (or the string value if the `--string` flag is used)
path: PathBuf,
/// The format of the file; defaults to the file extension
format: Option<String>,
/// If the argument should be treated as a string, rather than a file path
#[clap(short, long)]
string: bool,
}
#[async_trait]
impl Run for Detect {
async fn run(&self) -> Result {
let node = if self.string {
let string = self
.path
.to_str()
.ok_or_else(|| eyre!("Value is not valid Unicode"))?
.into();
Node::String(string)
} else {
codecs::from_path(&self.path, self.format.as_deref(), None).await?
};
let detections = detect(&node).await?;
result::value(detections)
}
}
/// Enrich nodes within a file or string
#[derive(Debug, Parser)]
pub struct Enrich {
/// The path to the file (or the string value if the `--string` flag is used)
path: PathBuf,
/// The format of the file; defaults to the file extension
format: Option<String>,
/// If the argument should be treated as a string, rather than a file path
#[clap(short, long)]
string: bool,
/// The token (or name of environment variable) required to access the resource
///
/// Only necessary if authentication is required for the resource. Defaults to
/// using the environment variable corresponding to the provider of the resource
/// e.g. `GITHUB_TOKEN`.
#[clap(long)]
token: Option<String>,
}
#[async_trait]
impl Run for Enrich {
async fn run(&self) -> Result {
let node = if self.string {
let string = self
.path
.to_str()
.ok_or_else(|| eyre!("Value is not valid Unicode"))?
.into();
Node::String(string)
} else {
codecs::from_path(&self.path, self.format.as_deref(), None).await?
};
let detections = detect(&node).await?;
let mut nodes: Vec<Node> = Vec::with_capacity(detections.len());
let options = EnrichOptions {
token: self.token.clone(),
};
for detection in detections.into_iter() {
let node = enrich(detection.node, Some(options.clone())).await?;
nodes.push(node);
}
result::value(nodes)
}
}
/// Import content from a remote source to a local path
#[derive(Debug, Parser)]
pub struct Import {
/// The source identifier e.g. `github:org/name@v1.2.0`
source: String,
/// The local path to import file/s to e.g. `data`
#[clap(default_value = ".")]
path: PathBuf,
/// The token (or name of environment variable) required to access the resource
///
/// Only necessary if authentication is required for the resource. Defaults to
/// using the environment variable corresponding to the provider of the resource
/// e.g. `GITHUB_TOKEN`.
#[clap(long)]
token: Option<String>,
}
#[async_trait]
impl Run for Import {
async fn run(&self) -> Result {
let (.., node) = resolve(&self.source).await?;
let options = ImportOptions {
token: self.token.clone(),
};
import(&node, &self.path, Some(options)).await?;
result::nothing()
}
}
/// Export content from a local path to a remote source
#[derive(Debug, Parser)]
pub struct Export {
/// The source identifier e.g. `github:org/name@v1.2.0`
source: String,
/// The local path to export file/s from e.g. `report.md`
#[clap(default_value = ".")]
path: PathBuf,
/// The token (or name of environment variable) required to access the resource
///
/// Only necessary if authentication is required for the resource. Defaults to
/// using the environment variable corresponding to the provider of the resource
/// e.g. `GITHUB_TOKEN`.
#[clap(long)]
token: Option<String>,
}
#[async_trait]
impl Run for Export {
async fn run(&self) -> Result {
let (.., node) = resolve(&self.source).await?;
let options = ExportOptions {
token: self.token.clone(),
};
export(&node, &self.path, Some(options)).await?;
result::nothing()
}
}
/// Schedule import and/or export between remote source and a local path
#[derive(Debug, Parser)]
pub struct Cron {
/// The action to take at the scheduled time
#[clap(possible_values=provider::ACTIONS)]
action: String,
/// The schedule on which to perform the action
schedule: String,
/// The source identifier e.g. `github:org/name`
source: String,
/// The local path to synchronize with the source
#[clap(default_value = ".")]
path: PathBuf,
}
#[async_trait]
impl Run for Cron {
async fn run(&self) -> Result {
let (.., node) = resolve(&self.source).await?;
let (subscriber, canceller) = mpsc::channel(1);
events::subscribe_to_interrupt(subscriber).await;
cron(&node, &self.path, &self.action, &self.schedule, canceller).await?;
result::nothing()
}
}
}