graphforge-cli 0.6.0

GraphForge command-line interface
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! The porcelain verbs that talk to a Hub: `push`, `pull` and `log --remote`.
use super::local::{upstream_of, write_log};
use super::render::{LogEntry, history_order};
use super::{
    BranchSelect, HubFlags, LogArgs, PullArgs, PushArgs, bound_uuid, created_at, derived_uuid,
    emit, idempotency_conflict, intent_digest, receipt_json, report_operation, resolve_branch,
    short,
};
use crate::CliRuntimeError;
use crate::hub_clone::remote_read::{RemoteHead, RemoteRepository, RemoteRequest, read_remote};
use crate::hub_http::Transport;
use crate::hub_publish::PublishArgs;
use arrow::array::{Array as _, StringArray};
use graphforge_api::{
    CancellationToken, DiscoveryResearchVersionRequest, FetchResearchBranchRequest,
    FetchedResearchBranch, GfError, GraphForge, PortableLimits, PortableMode,
    PreviewResearchUpstreamRequest, ResearchRegistry, ResearchUpstreamScope,
    ResearchUpstreamSelection, SetResearchTagRequest, UpdateResearchBranchRequest,
};
use graphforge_hub_publish::PublishToken;
use serde_json::json;
use std::collections::BTreeSet;
use std::io::Write;
use std::path::PathBuf;
use uuid::Uuid;

/// Dispatch a Hub verb for the production process: open the Project and use the
/// real transport and credential sources.
pub(crate) fn run_remote(
    command: crate::Command,
    project: Option<PathBuf>,
    project_dir: Option<PathBuf>,
    json_output: bool,
    output: &mut dyn Write,
    diagnostics: &mut crate::Diagnostics<'_>,
) -> Result<(), CliRuntimeError> {
    if let crate::Command::Push(args) = &command {
        crate::hub_publish::require_push_visibility(&args.visibility)?;
    }
    let path = crate::resolve_project_path(project, project_dir)?;
    let path = path
        .to_str()
        .ok_or_else(|| GfError::Validation("--project must be valid UTF-8".into()))?;
    let mut graph = GraphForge::new(Some(path))?;
    diagnostics.warn(&graph.open_warnings());
    run_remote_with(
        &crate::hub_http::HubTransport::new(),
        &|hub: &HubFlags| crate::hub_publish::publish_token(hub.token_env.as_deref()),
        &mut graph,
        command,
        json_output,
        output,
    )
}

/// Dispatch a Hub verb over a given transport and publish-credential source.
pub(crate) fn run_remote_with(
    transport: &dyn Transport,
    publish_token: &dyn Fn(&HubFlags) -> Result<Option<PublishToken>, GfError>,
    graph: &mut GraphForge,
    command: crate::Command,
    json_output: bool,
    output: &mut dyn Write,
) -> Result<(), CliRuntimeError> {
    match command {
        crate::Command::Push(args) => {
            crate::hub_publish::require_push_visibility(&args.visibility)?;
            push(
                transport,
                graph,
                &args,
                || publish_token(&args.hub),
                json_output,
                output,
            )
        }
        crate::Command::Pull(args) => Ok(pull(transport, graph, &args, json_output, output)?),
        crate::Command::Log(args) => Ok(log_remote(transport, graph, &args, json_output, output)?),
        _ => unreachable!("only Hub porcelain verbs are dispatched here"),
    }
}

/// `--ref` names a Branch by label (ADR 0061), so it selects the Branch just as
/// `--branch` does; naming two different Branches is an error.
fn branch_flag<'a>(
    select: &'a BranchSelect,
    git_ref: Option<&'a str>,
) -> Result<Option<&'a str>, GfError> {
    match (select.branch.as_deref(), git_ref) {
        (Some(branch), Some(reference)) if branch != reference => Err(GfError::Validation(
            "--ref names a Branch by its label; it must equal --branch".into(),
        )),
        (branch, reference) => Ok(branch.or(reference)),
    }
}

pub(crate) fn repository_of(
    registry: &ResearchRegistry,
    branch: Uuid,
    given: Option<&str>,
    hub: &HubFlags,
) -> Result<String, GfError> {
    if given.is_none()
        && registry
            .remote_branches
            .values()
            .filter(|remote| remote.branch_uuid == branch)
            .map(|remote| &remote.repository_url)
            .collect::<BTreeSet<_>>()
            .len()
            > 1
    {
        return Err(GfError::Validation(
            "GF_RESEARCH_UPSTREAM_AMBIGUOUS: the Branch has more than one upstream repository; name the destination explicitly".into(),
        ));
    }
    let repository = match given {
        Some(repository) => repository.to_owned(),
        None => upstream_of(registry, branch)
            .map(|remote| remote.repository_url.clone())
            .ok_or_else(|| {
                GfError::Validation(
                    "GF_RESEARCH_UPSTREAM_UNSET: the Branch has no upstream; name the repository, for example `gf push owner/repository`"
                        .into(),
                )
            })?,
    };
    Ok(match &hub.hub {
        Some(hub) if !repository.contains("://") => {
            format!("{}/{repository}", hub.trim_end_matches('/'))
        }
        _ => repository,
    })
}

/// The arguments `gf publish` would take for this push.
pub(crate) fn push_args(
    registry: &ResearchRegistry,
    args: &PushArgs,
) -> Result<PublishArgs, GfError> {
    let branch = resolve_branch(
        registry,
        branch_flag(&args.select, args.git_ref.as_deref())?,
    )?;
    // A Branch label is its ref: publish names the Branch by it.
    let label = registry.branches[&branch].label.clone();
    Ok(PublishArgs {
        hub: None,
        visibility: args.visibility.clone(),
        rewrite: args.rewrite,
        prune: args.prune,
        check_fork_origin: None,
        repository: Some(repository_of(
            registry,
            branch,
            args.repository.as_deref(),
            &args.hub,
        )?),
        git_ref: Some(label),
        version_uuid: None,
        fork_of: None,
        operation_uuid: args.operation_uuid.clone(),
        staging_directory: args.staging_directory.clone(),
        protection_bypass_env: args.hub.protection_bypass_env.clone(),
        previews: Vec::new(),
    })
}

/// `gf push`: `gf publish` with the Branch's upstream as its defaults.
pub(crate) fn push(
    transport: &dyn Transport,
    graph: &mut GraphForge,
    args: &PushArgs,
    token: impl FnOnce() -> Result<Option<PublishToken>, GfError>,
    json_output: bool,
    output: &mut dyn Write,
) -> Result<(), CliRuntimeError> {
    let publish = push_args(&graph.research_version_retention()?, args)?;
    let (_, base) = crate::hub_http::parse_input(publish.repository()?)?;
    let bypass = crate::hub_http::DiscoveryCredentials::load(
        &base,
        None,
        publish.protection_bypass_env.as_deref(),
        |name| std::env::var(name),
    )?;
    crate::hub_publish::push_with_credentials(
        transport,
        &publish,
        token,
        bypass.as_ref(),
        |publish, environment| {
            crate::hub_publish::publish_and_report(
                transport,
                graph,
                publish,
                environment,
                json_output,
                output,
            )
        },
    )
}

/// A served tag whose name a local tag holds for another Version refuses the pull.
fn check_tags(registry: &ResearchRegistry, remote: &RemoteRepository) -> Result<(), GfError> {
    for tag in &remote.lineage.tags {
        if let (Some(local), Ok(served)) = (
            registry.tags.get(&tag.name),
            Uuid::parse_str(&tag.version_uuid),
        ) && *local != served
        {
            return Err(GfError::Validation(format!(
                "GF_RESEARCH_TAG_CONFLICT: the Hub serves tag '{}' on another Version than the local tag; delete the local tag (`gf tag -d {}`) and pull again",
                tag.name, tag.name
            )));
        }
    }
    Ok(())
}

/// Install the served tags whose Versions this Project now knows.
fn install_tags(graph: &mut GraphForge, remote: &RemoteRepository) -> Result<(), GfError> {
    for tag in &remote.lineage.tags {
        let registry = graph.research_version_retention()?;
        let Ok(version) = Uuid::parse_str(&tag.version_uuid) else {
            continue;
        };
        if registry.tags.contains_key(&tag.name) || !registry.identities.contains_key(&version) {
            continue;
        }
        graph.set_research_tag(
            &SetResearchTagRequest {
                operation_uuid: Uuid::now_v7(),
                expected_generation_uuid: graph.committed_generation_identity()?.generation_uuid,
                name: tag.name.clone(),
                version_uuid: Some(version),
            },
            &CancellationToken::new(),
        )?;
    }
    Ok(())
}

fn column<'a>(
    batch: &'a arrow::record_batch::RecordBatch,
    name: &str,
) -> Result<&'a StringArray, GfError> {
    batch
        .column_by_name(name)
        .and_then(|column| column.as_any().downcast_ref::<StringArray>())
        .ok_or_else(|| GfError::Execution(format!("the upstream preview has no {name} column")))
}

/// The durable first step of a pull: admit the Hub's head of the ref, with the tags
/// it serves. Its operation identity derives from the pull's, so a pull that was
/// interrupted after this step resumes from the fetch it recorded.
pub(crate) fn fetch_step(
    graph: &mut GraphForge,
    branch: Uuid,
    remote: &RemoteRepository,
    head: &RemoteHead,
    operation: Uuid,
    cancel: &CancellationToken,
) -> Result<FetchedResearchBranch, GfError> {
    graph.fetch_research_branch(
        &FetchResearchBranchRequest {
            operation_uuid: derived_uuid(operation, "fetch"),
            expected_generation_uuid: graph.committed_generation_identity()?.generation_uuid,
            branch_uuid: branch,
            repository_url: &remote.repository_url,
            discovery: DiscoveryResearchVersionRequest {
                manifest_json: &remote.manifest_bytes,
                refs_json: &remote.refs_bytes,
                lineage_json: &remote.lineage_bytes,
                expected_repository: &remote.identity,
                version_uuid: &head.version_uuid,
                package: &head.package,
                discovery_limits: remote.limits,
                portable_limits: PortableLimits::default(),
                mode: PortableMode::Full,
                cancelled: None,
                scratch: None,
            },
        },
        cancel,
    )
}

/// `gf pull`: fetch the Hub's head of the Branch's ref, preview it as an upstream
/// and record a Version that incorporates every compatible change.
#[allow(clippy::too_many_lines)]
pub(crate) fn pull(
    transport: &dyn Transport,
    graph: &mut GraphForge,
    args: &PullArgs,
    json_output: bool,
    output: &mut dyn Write,
) -> Result<(), GfError> {
    let registry = graph.research_version_retention()?;
    let branch = resolve_branch(
        &registry,
        branch_flag(&args.select, args.git_ref.as_deref())?,
    )?;
    let label = registry.branches[&branch].label.clone();
    let repository = repository_of(&registry, branch, args.repository.as_deref(), &args.hub)?;
    let operation = report_operation(args.operation_uuid.as_deref(), json_output, output)?;
    let (author, committer) = crate::identity::resolve_from_process(&args.identity)?;
    // The merge Version's identity is bound to the complete request, so an earlier
    // run of this identity is replayed from the local ledger, with no network, only
    // when it was this exact pull.
    let intent = intent_digest(
        "pull",
        &json!({
            "branch": branch,
            "repository": repository,
            "author": author,
            "committer": committer,
        }),
    );
    let version_uuid = bound_uuid(operation, "version", &intent);
    if let Some(receipt) = registry.receipts.get(&operation) {
        if receipt.version_uuid != Some(version_uuid) {
            return Err(idempotency_conflict());
        }
        let parents = registry
            .versions
            .get(&version_uuid)
            .map(|version| version.parents.clone())
            .unwrap_or_default();
        let mut value = receipt_json(receipt, true);
        value["parents"] = json!(parents);
        value["incorporated"] = json!(
            registry
                .upstream
                .reviews
                .get(&operation)
                .map_or(0, |review| review.fields.len())
        );
        value["conflicts"] = json!([]);
        let merged = parents.get(1).map_or_else(String::new, short);
        return emit(
            output,
            json_output,
            &value,
            &format!("Merged {merged} into {label}: {}", short(&version_uuid)),
        );
    }
    let scratch = tempfile::tempdir()
        .map_err(|_| GfError::Storage("cannot create a download directory".into()))?;
    let request = RemoteRequest {
        repository: &repository,
        hub: args.hub.hub.as_deref(),
        token_env: args.hub.token_env.as_deref(),
        protection_bypass_env: args.hub.protection_bypass_env.as_deref(),
    };
    let (remote, head) = read_remote(transport, &request, Some((&label, scratch.path())))?;
    let head = head.ok_or_else(|| GfError::Execution("the remote head was not read".into()))?;
    let remote_head = Uuid::parse_str(&head.version_uuid)
        .map_err(|_| GfError::Validation("the remote head is not a Version UUID".into()))?;
    let local_head = registry.heads[&branch];
    check_tags(&registry, &remote)?;
    if local_head == remote_head || registry.ancestors(local_head).contains(&remote_head) {
        install_tags(graph, &remote)?;
        return emit(
            output,
            json_output,
            &json!({"up_to_date": true, "branch_uuid": branch, "head_version_uuid": local_head}),
            "Already up to date",
        );
    }
    let cancel = CancellationToken::new();
    let fetched = fetch_step(graph, branch, &remote, &head, operation, &cancel)?;
    let preview_request = PreviewResearchUpstreamRequest {
        branch_uuid: branch,
        scope: ResearchUpstreamScope::Branch,
        remote: Some(fetched.binding.clone()),
    };
    let preview = graph.preview_research_upstream(&preview_request, &cancel)?;
    let batch = &preview.batches[0];
    let (kinds, fields, changes, evidence) = (
        column(batch, "object_kind")?,
        column(batch, "field")?,
        column(batch, "change")?,
        column(batch, "required_evidence_acknowledgements")?,
    );
    let mut blocking = Vec::new();
    let mut adoptable = 0_usize;
    let mut acknowledge = BTreeSet::new();
    for row in 0..batch.num_rows() {
        match changes.value(row) {
            change @ ("conflict" | "dependency_unavailable") => {
                blocking.push(format!(
                    "{}:{} ({change})",
                    kinds.value(row),
                    fields.value(row)
                ));
            }
            "upstream" | "equivalent" => {
                adoptable += 1;
                let needed: Vec<Uuid> = serde_json::from_str(evidence.value(row))
                    .map_err(|_| GfError::Execution("malformed evidence requirements".into()))?;
                acknowledge.extend(needed);
            }
            _ => {}
        }
    }
    if !blocking.is_empty() {
        let shown = blocking
            .iter()
            .take(10)
            .cloned()
            .collect::<Vec<_>>()
            .join(", ");
        return Err(GfError::Validation(format!(
            "the upstream has {} change(s) that cannot be adopted automatically: {shown}; the fetch is recorded, so resolve them explicitly with `gf research upstream update --file`",
            blocking.len()
        )));
    }
    if adoptable == 0 {
        return Err(GfError::Validation(
            "the upstream head changes no field; incorporate it explicitly with `gf research upstream update --file`"
                .into(),
        ));
    }
    let digest_hex = batch
        .schema()
        .metadata()
        .get("graphforge.upstream.preview_sha256")
        .cloned()
        .ok_or_else(|| GfError::Execution("the upstream preview has no digest".into()))?;
    let mut preview_sha256 = [0_u8; 32];
    for (index, byte) in preview_sha256.iter_mut().enumerate() {
        *byte = digest_hex
            .get(index * 2..index * 2 + 2)
            .and_then(|pair| u8::from_str_radix(pair, 16).ok())
            .ok_or_else(|| GfError::Execution("malformed upstream preview digest".into()))?;
    }
    let update = UpdateResearchBranchRequest {
        operation_uuid: operation,
        expected_generation_uuid: graph.committed_generation_identity()?.generation_uuid,
        version_uuid,
        preview: preview_request,
        preview_sha256,
        selection: ResearchUpstreamSelection::AllCompatible,
        acknowledge_evidence: acknowledge,
        actor_uuid: derived_uuid(operation, "actor"),
        created_at: created_at(operation),
        explanation: format!("gf pull {repository} {label}"),
        author: Some(author),
        committer: Some(committer),
        label: None,
        description: Some(format!("Merge {label} of {repository}")),
    };
    // The served tags were installed with the fetch, in one publication with its admission.
    let receipt = graph.update_research_branch(&update, &cancel)?;
    let mut value = receipt_json(&receipt, false);
    value["parents"] = json!([local_head, remote_head]);
    value["incorporated"] = json!(adoptable);
    value["conflicts"] = json!([]);
    emit(
        output,
        json_output,
        &value,
        &format!(
            "Merged {} into {label}: {}",
            short(&remote_head),
            short(&version_uuid)
        ),
    )
}

/// `gf log --remote`: walk the Hub's published lineage from the ref's head.
fn log_remote(
    transport: &dyn Transport,
    graph: &GraphForge,
    args: &LogArgs,
    json_output: bool,
    output: &mut dyn Write,
) -> Result<(), GfError> {
    let registry = graph.research_version_retention()?;
    let branch = resolve_branch(
        &registry,
        branch_flag(&args.select, args.git_ref.as_deref())?,
    )?;
    let label = registry.branches[&branch].label.clone();
    let given = args.remote.as_deref().filter(|text| !text.is_empty());
    let repository = repository_of(&registry, branch, given, &args.hub)?;
    let (remote, _) = read_remote(
        transport,
        &RemoteRequest {
            repository: &repository,
            hub: args.hub.hub.as_deref(),
            token_env: args.hub.token_env.as_deref(),
            protection_bypass_env: args.hub.protection_bypass_env.as_deref(),
        },
        None,
    )?;
    let lineage = &remote.lineage;
    let start = match &args.version {
        Some(text) => lineage
            .tags
            .iter()
            .find(|tag| tag.name == *text)
            .map_or_else(|| text.clone(), |tag| tag.version_uuid.clone()),
        None => lineage
            .branches
            .iter()
            .find(|candidate| candidate.ref_name == label)
            .map(|candidate| candidate.head_version_uuid.clone())
            .ok_or_else(|| {
                GfError::Validation(format!("the repository publishes no ref '{label}'"))
            })?,
    };
    let order = history_order(
        start,
        args.all,
        |version| {
            lineage
                .version(version)
                .map(|record| record.parents.clone())
        },
        |_| None,
    );
    let entries: Vec<LogEntry> = order
        .iter()
        .filter_map(|version| lineage.version(version))
        .take(args.max_count.unwrap_or(usize::MAX))
        .map(|record| LogEntry {
            version_uuid: record.version_uuid.clone(),
            parents: record.parents.clone(),
            author: record
                .author
                .as_ref()
                .and_then(|person| serde_json::to_value(person).ok()),
            committer: record
                .committer
                .as_ref()
                .and_then(|person| serde_json::to_value(person).ok()),
            created_at: None,
            label: None,
            description: None,
            tags: lineage
                .tags
                .iter()
                .filter(|tag| tag.version_uuid == record.version_uuid)
                .map(|tag| tag.name.clone())
                .collect(),
            kind: record.kind.clone(),
        })
        .collect();
    write_log(&entries, json_output, output)
}