link-cli 1.0.5

A CLI tool and reusable library for links manipulation backed by a LiNo-notation doublet storage engine.
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
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Link CLI - A command-line tool for links manipulation
//!
//! This is the Rust implementation of the link-cli tool, providing
//! similar functionality to the C# version.

use anyhow::{anyhow, bail, Result};
use link_cli::cli::{Cli, CliCommand};
use link_cli::import_lino_file;
use link_cli::protocol::{
    export_store_file, import_store_file, AcceptedProtocols, BinaryLinoOptions, BinaryLinoProtocol,
    LinksClient, LinksServer, LinoProtocol, ServerOptions, TextLinoProtocol,
};
use link_cli::{
    make_triggers_database_filename, CommitMode, LogRetentionPolicy, NamedTypeLinks,
    NamedTypesDecorator, PersistentTransformationDecorator, PersistentTransformationKind,
    QueryProcessor, TransactionsDecorator, TriggerStore, VersionControlDecorator,
};
use std::path::PathBuf;

fn main() -> Result<()> {
    let cli = match Cli::parse()? {
        CliCommand::Run(cli) => *cli,
        CliCommand::Help => {
            Cli::print_help();
            return Ok(());
        }
        CliCommand::Version => {
            println!("{}", Cli::version_text());
            return Ok(());
        }
    };

    if cli.trigger_command_count() > 1 {
        bail!("Only one of --always, --once, or --never can be used at a time.");
    }

    if cli.serve.is_some() && cli.connect.is_some() {
        bail!("--serve and --connect cannot be used together.");
    }
    if let Some(address) = &cli.connect {
        if cli.indexed_lookups {
            bail!("--indexed-lookups applies to local stores; enable it on the server.");
        }
        return run_client(&cli, address);
    }

    let vc_requested = cli.vc_requested();
    let transactions_requested = cli.transactions_requested();

    let commit_mode = parse_commit_mode(cli.commit_mode.as_deref())?;
    let retention_policy = parse_retention(cli.retention.as_deref())?;

    if vc_requested {
        run_with_vc(&cli, commit_mode, retention_policy)
    } else if transactions_requested {
        run_with_transactions(&cli, commit_mode, retention_policy)
    } else {
        run_bare(&cli)
    }
}

fn parse_commit_mode(raw: Option<&str>) -> Result<CommitMode> {
    match raw.map(|s| s.trim()).filter(|s| !s.is_empty()) {
        None => Ok(CommitMode::Sync),
        Some(value) if value.eq_ignore_ascii_case("sync") => Ok(CommitMode::Sync),
        Some(value) if value.eq_ignore_ascii_case("async") => Ok(CommitMode::Async),
        Some(other) => bail!("Invalid --commit-mode value '{other}'. Use 'sync' or 'async'."),
    }
}

fn parse_retention(raw: Option<&str>) -> Result<LogRetentionPolicy> {
    match raw.map(|s| s.trim()).filter(|s| !s.is_empty()) {
        None => Ok(LogRetentionPolicy::Infinite),
        Some(value) => LogRetentionPolicy::parse(value)
            .map_err(|e| anyhow!("Invalid --retention value '{value}': {e}")),
    }
}

fn open_named_storage(path: impl AsRef<std::path::Path>, cli: &Cli) -> Result<NamedTypesDecorator> {
    let storage = NamedTypesDecorator::new(path, cli.trace)?;
    Ok(if cli.indexed_lookups {
        storage.with_indexed_lookups()
    } else {
        storage
    })
}

fn run_bare(cli: &Cli) -> Result<()> {
    let storage = open_named_storage(&cli.db, cli)?;
    finish(cli, storage)
}

/// Resolved path of the trigger sidecar store: `--triggers-file` when given,
/// `<db>.triggers.links` otherwise.
fn triggers_path(cli: &Cli) -> PathBuf {
    cli.triggers_file
        .clone()
        .map(PathBuf::from)
        .unwrap_or_else(|| make_triggers_database_filename(&cli.db))
}

/// Mirrors `persistentTransformationsEnabled` in the C# tool: any explicit flag
/// turns the layer on, and so does an already existing trigger store, so that
/// triggers stored by an earlier invocation keep firing without repeating
/// `--triggers`.
fn persistent_transformations_enabled(cli: &Cli) -> bool {
    cli.persistent_transformations_requested() || triggers_path(cli).exists()
}

/// Runs the query pipeline over `storage`, wrapping it in a
/// [`PersistentTransformationDecorator`] first when triggers are enabled.
///
/// The wrap happens here rather than in the three entry paths so that the
/// decorator always sits *outermost* — above the transactions and
/// version-control layers — exactly like in the C# tool, where every replayed
/// substitution is journalled like any other write.
fn finish<S>(cli: &Cli, storage: S) -> Result<()>
where
    S: NamedTypeLinks,
{
    if !persistent_transformations_enabled(cli) {
        let mut storage = storage;
        if let Some(address) = &cli.serve {
            return run_server(cli, address, &mut storage);
        }
        run_query_pipeline(cli, &mut storage)?;
        storage.save()?;
        return Ok(());
    }

    let trigger_store = if cli.embed_triggers {
        TriggerStore::Embedded
    } else {
        TriggerStore::sidecar(triggers_path(cli), cli.trace)?
    };
    let mut storage = PersistentTransformationDecorator::new(storage, trigger_store, cli.trace)
        .with_auto_create_missing_references(cli.auto_create_missing_references);

    if let Some(address) = &cli.serve {
        return run_server(cli, address, &mut storage);
    }
    run_query_pipeline_with(cli, &mut storage, run_trigger_command)?;
    storage.save()?;
    Ok(())
}

/// Handles `--always`, `--once` and `--never`.
///
/// Returns `true` when the command was terminal, i.e. the query was consumed as
/// a trigger definition and must not also be executed against the database.
fn run_trigger_command<S>(
    cli: &Cli,
    storage: &mut PersistentTransformationDecorator<S>,
    query: Option<&str>,
) -> Result<bool>
where
    S: NamedTypeLinks,
{
    if cli.trigger_command_count() == 0 {
        return Ok(false);
    }

    let query = query.filter(|query| !query.trim().is_empty());
    let Some(query) = query else {
        bail!("--always, --once, and --never require a query.");
    };

    if cli.always || cli.once {
        let kind = if cli.always {
            PersistentTransformationKind::Always
        } else {
            PersistentTransformationKind::Once
        };
        let root = storage.store_trigger(kind, query)?;
        println!("{kind} persistent transformation trigger stored: {root}");
    } else {
        let removed = storage.remove_triggers(query)?;
        println!("Persistent transformation triggers removed: {removed}");
    }

    Ok(true)
}

fn run_with_transactions(
    cli: &Cli,
    commit_mode: CommitMode,
    retention_policy: LogRetentionPolicy,
) -> Result<()> {
    let data_links = open_named_storage(&cli.db, cli)?;
    let log_path = cli
        .transactions_file
        .clone()
        .map(std::path::PathBuf::from)
        .unwrap_or_else(|| TransactionsDecorator::make_transitions_database_filename(&cli.db));
    let log_links = open_named_storage(&log_path, cli)?;
    let mut tx = TransactionsDecorator::new(
        data_links,
        log_links,
        retention_policy,
        commit_mode,
        cli.trace,
    )?;

    if cli.show_log {
        for transition in tx.log() {
            println!(
                "{}\t{}\t{:?}\t{:032x}\t({},{},{}) -> ({},{},{})",
                transition.sequence,
                transition.timestamp_ms,
                transition.kind,
                transition.transaction_id,
                transition.before.index,
                transition.before.source,
                transition.before.target,
                transition.after.index,
                transition.after.source,
                transition.after.target,
            );
        }
        tx.save()?;
        return Ok(());
    }

    finish(cli, tx)
}

fn run_with_vc(
    cli: &Cli,
    commit_mode: CommitMode,
    retention_policy: LogRetentionPolicy,
) -> Result<()> {
    let data_links = open_named_storage(&cli.db, cli)?;
    let log_path = cli
        .transactions_file
        .clone()
        .map(std::path::PathBuf::from)
        .unwrap_or_else(|| TransactionsDecorator::make_transitions_database_filename(&cli.db));
    let log_links = open_named_storage(&log_path, cli)?;
    let tx = TransactionsDecorator::new(
        data_links,
        log_links,
        retention_policy,
        commit_mode,
        cli.trace,
    )?;
    let vc_path = cli
        .vc_file
        .clone()
        .map(std::path::PathBuf::from)
        .unwrap_or_else(|| {
            VersionControlDecorator::make_version_control_database_filename(&cli.db)
        });
    let vc_links = open_named_storage(&vc_path, cli)?;
    let mut vc = VersionControlDecorator::new(tx, vc_links, cli.trace)?;

    // 1) --checkout (resolves seq or tag).
    if let Some(checkout_point) = cli.checkout.as_deref() {
        let seq = resolve_sequence(&vc, checkout_point)
            .ok_or_else(|| anyhow!("Unknown checkout point '{checkout_point}'."))?;
        vc.checkout(seq)?;
        if cli.trace {
            println!("Checked out seq {seq} on branch '{}'.", vc.current_branch());
        }
    }

    // 2) --branch [--branch-from] (creates if missing, then switches).
    if let Some(branch_name) = cli.branch.as_deref() {
        let exists = vc.list_branches().iter().any(|b| b.name == branch_name);
        if !exists {
            vc.branch(branch_name, cli.branch_from)?;
            if cli.trace {
                println!("Created branch '{branch_name}'.");
            }
        }
        vc.switch_branch(branch_name)?;
        if cli.trace {
            println!("Switched to branch '{branch_name}'.");
        }
    }

    // 3) --tag.
    if let Some(tag_spec) = cli.tag.as_deref() {
        let (name, seq) = match tag_spec.find('=') {
            None => (tag_spec.to_string(), None),
            Some(eq) => {
                let (name_part, value_part) = tag_spec.split_at(eq);
                let value_part = &value_part[1..];
                let resolved = resolve_sequence(&vc, value_part)
                    .ok_or_else(|| anyhow!("Unknown tag point '{value_part}'."))?;
                (name_part.to_string(), Some(resolved))
            }
        };
        vc.tag(&name, seq)?;
        if cli.trace {
            let resolved = seq.unwrap_or_else(|| vc.current_sequence());
            println!("Tagged '{name}' at seq {resolved}.");
        }
    }

    // 4) --list-branches / --list-tags (terminal).
    if cli.list_branches {
        let current = vc.current_branch().to_string();
        for info in vc.list_branches() {
            let marker = if info.name == current { "*" } else { " " };
            let parent = info.parent.clone().unwrap_or_else(|| "-".to_string());
            println!(
                "{} {}\tparent={}\tfork={}\thead={}",
                marker, info.name, parent, info.fork_seq, info.head
            );
        }
        vc.save()?;
        return Ok(());
    }

    if cli.list_tags {
        for (name, seq) in vc.list_tags() {
            println!("{name}\t{seq}");
        }
        vc.save()?;
        return Ok(());
    }

    // 5) --log.
    if cli.show_log {
        for transition in vc.transactions().log() {
            println!(
                "{}\t{}\t{:?}\t{:032x}\t({},{},{}) -> ({},{},{})",
                transition.sequence,
                transition.timestamp_ms,
                transition.kind,
                transition.transaction_id,
                transition.before.index,
                transition.before.source,
                transition.before.target,
                transition.after.index,
                transition.after.source,
                transition.after.target,
            );
        }
        vc.save()?;
        return Ok(());
    }

    finish(cli, vc)
}

fn resolve_sequence(vc: &VersionControlDecorator, point: &str) -> Option<i64> {
    let trimmed = point.trim();
    if trimmed.is_empty() {
        return None;
    }
    if let Ok(direct) = trimmed.parse::<i64>() {
        return Some(direct);
    }
    vc.try_get_tag(trimmed)
}

fn run_query_pipeline<S>(cli: &Cli, storage: &mut S) -> Result<()>
where
    S: NamedTypeLinks,
{
    run_query_pipeline_with(cli, storage, |_, _, _| Ok(false))
}

/// The query pipeline, with a hook that may consume the query before it reaches
/// the [`QueryProcessor`].
///
/// `trigger_stage` runs where the C# tool runs its trigger commands: after
/// `--structure`, so `clink --structure` keeps working unchanged, and before
/// the query is processed, so `--always '…'` stores the query instead of
/// applying it. Returning `true` ends the run after the LiNo output is written.
fn run_query_pipeline_with<S, F>(cli: &Cli, storage: &mut S, trigger_stage: F) -> Result<()>
where
    S: NamedTypeLinks,
    F: FnOnce(&Cli, &mut S, Option<&str>) -> Result<bool>,
{
    if cli.before {
        storage.print_all_lino()?;
    }

    import_inputs(cli, storage)?;

    if let Some(link_id) = cli.structure {
        let structure_formatted = storage.format_structure(link_id)?;
        println!("{structure_formatted}");
        export_outputs(cli, storage)?;
        return Ok(());
    }

    let effective_query = cli.query.as_deref().or(cli.query_arg.as_deref());

    if trigger_stage(cli, storage, effective_query)? {
        export_outputs(cli, storage)?;
        return Ok(());
    }

    let mut changes_list = Vec::new();

    if let Some(query) = effective_query {
        if !query.is_empty() {
            let processor = QueryProcessor::new(cli.trace)
                .with_auto_create_missing_references(cli.auto_create_missing_references);
            changes_list = processor.process_query(storage, query)?;
        }
    }

    if cli.changes && !changes_list.is_empty() {
        for (before_link, after_link) in &changes_list {
            storage.print_change_lino(before_link, after_link)?;
        }
    }

    if cli.after {
        storage.print_all_lino()?;
    }

    export_outputs(cli, storage)?;

    Ok(())
}

/// Imports the store archive of `--import-binary`, then the LiNo file of
/// `--in`.
fn import_inputs<S: NamedTypeLinks>(cli: &Cli, storage: &mut S) -> Result<()> {
    if let Some(input_path) = &cli.binary_input {
        import_store_file(storage, input_path)?;
    }
    if let Some(input_path) = &cli.lino_input {
        import_lino_file(storage, input_path)?;
    }
    Ok(())
}

/// Writes the whole store to the LiNo file of `--out` and the store archive
/// of `--export-binary`.
fn export_outputs<S: NamedTypeLinks>(cli: &Cli, storage: &mut S) -> Result<()> {
    if let Some(output_path) = &cli.lino_output {
        storage.write_lino_output(output_path)?;
    }
    if let Some(output_path) = &cli.binary_output {
        export_store_file(storage, output_path)?;
    }
    Ok(())
}

/// The binary options selected by `--external-references`, `--arity` and
/// `--packed-widths`.
fn binary_options(cli: &Cli) -> BinaryLinoOptions {
    BinaryLinoOptions::default()
        .with_external_references(cli.external_references)
        .with_arity(cli.arity)
        .with_packed_widths(cli.packed_widths)
}

/// `--connect`: sends the query to a server and prints the reply.
///
/// Any binary option implies `--protocol binary`.
fn run_client(cli: &Cli, address: &str) -> Result<()> {
    let options = binary_options(cli);
    let protocol: Box<dyn LinoProtocol> = match cli.protocol.as_deref().map(str::trim) {
        None if options == BinaryLinoOptions::default() => Box::new(TextLinoProtocol::new()),
        None => Box::new(BinaryLinoProtocol::with_options(options)),
        Some(name) if name.eq_ignore_ascii_case("text") => {
            if options != BinaryLinoOptions::default() {
                bail!("Binary protocol options require --protocol binary.");
            }
            Box::new(TextLinoProtocol::new())
        }
        Some(name) if name.eq_ignore_ascii_case("binary") => {
            Box::new(BinaryLinoProtocol::with_options(options))
        }
        Some(other) => bail!("Invalid --protocol value '{other}'. Use 'text' or 'binary'."),
    };
    let query = cli.query.as_deref().or(cli.query_arg.as_deref());
    let mut client = LinksClient::connect(address, protocol)?;
    let reply = client.query_text(query.unwrap_or_default())?;
    if !reply.is_empty() {
        println!("{reply}");
    }
    Ok(())
}

/// `--serve`: serves `storage` until the process is stopped.
fn run_server<S>(cli: &Cli, address: &str, storage: &mut S) -> Result<()>
where
    S: NamedTypeLinks,
{
    if cli.query.is_some() || cli.query_arg.is_some() {
        bail!("--serve does not take a query; send queries with --connect.");
    }
    let accept = match cli.protocol.as_deref().map(str::trim) {
        None => AcceptedProtocols::Any,
        Some(name) if name.eq_ignore_ascii_case("any") => AcceptedProtocols::Any,
        Some(name) if name.eq_ignore_ascii_case("text") => AcceptedProtocols::Text,
        Some(name) if name.eq_ignore_ascii_case("binary") => AcceptedProtocols::Binary,
        Some(other) => {
            bail!("Invalid --protocol value '{other}'. Use 'any', 'text' or 'binary'.")
        }
    };
    let options = ServerOptions {
        trace: cli.trace,
        auto_create_missing_references: cli.auto_create_missing_references,
        accept,
        ..ServerOptions::default()
    };
    let server = LinksServer::bind(address, options)?;
    println!("clink server listening on {}", server.local_addr()?);
    std::io::Write::flush(&mut std::io::stdout())?;
    server.serve(storage)?;
    storage.save()?;
    Ok(())
}