swh-graph 11.4.1

Compressed in-memory representation of the Software Heritage archive graph
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
/*
 * Copyright (C) 2025-2026  The Software Heritage developers
 * See the AUTHORS file at the top-level directory of this distribution
 * License: GNU General Public License version 3, or any later version
 * See top-level LICENSE file for more information
 */

use std::io::BufReader;
use std::path::PathBuf;

use anyhow::{anyhow, ensure, Context, Result};
use clap::{Parser, ValueEnum};

use swh_graph::graph::*;
use swh_graph::labels::{EdgeLabel, VisitStatus};
use swh_graph::properties;
use swh_graph::{NodeType, SWHID};

#[derive(ValueEnum, Clone, Debug, PartialEq, Eq)]
enum Direction {
    Forward,
    Bidirectional,
}

#[derive(ValueEnum, Clone, Debug, PartialEq, Eq)]
enum Labels {
    None,
    Bidirectional,
}

/// On-disk format of the graph. This should always be `Webgraph` unless testing.
#[derive(ValueEnum, Clone, Debug)]
enum GraphFormat {
    Webgraph,
    Json,
}

#[derive(Parser, Debug)]
/// Runs any of swh-graph's Minimal Perfect Hash functions
///
/// Lines in stdin are hashed one by one, and a decimal-encoded 64-bits integer is
/// written on the output for each of them.
///
/// If any of the input lines was not in the dataset used to build the MPH, then the result
/// will either be a silent hash collision or cause a non-zero exit.
struct Args {
    #[arg(long, value_enum, default_value_t = GraphFormat::Webgraph)]
    graph_format: GraphFormat,
    #[arg(long, default_value = "bidirectional")]
    direction: Direction,
    #[arg(long, default_value = "bidirectional")]
    labels: Labels,
    graph_path: PathBuf,
    /// Either SWHID or node id
    nodes: Vec<String>,
}

pub fn main() -> Result<()> {
    let args = Args::parse();

    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();

    log::info!("Loading graph");
    macro_rules! load_properties {
        ($graph:expr) => {
            $graph.init_properties().load_properties(|properties| {
                properties
                    .load_maps::<swh_graph::mph::DynMphf>()
                    .context("Could not load maps")?
                    .opt_load_timestamps()
                    .context("Could not load timestamp properties")?
                    .opt_load_persons()
                    .context("Could not load person properties")?
                    .opt_load_contents()
                    .context("Could not load content properties")?
                    .opt_load_strings()
                    .context("Could not load string properties")
            })
        };
    }

    match args.graph_format {
        GraphFormat::Webgraph => match args.direction {
            Direction::Bidirectional => {
                let graph =
                    SwhBidirectionalGraph::new(&args.graph_path).context("Could not load graph")?;
                let graph = load_properties!(graph)?;
                match args.labels {
                    Labels::Bidirectional => {
                        let graph = graph
                            .load_properties(|properties| {
                                properties
                                    .load_label_names()
                                    .context("Could not load label names")
                            })?
                            .load_labels()
                            .context("Could not load labels")?;
                        for swhid_or_node in args.nodes {
                            let (node, swhid) = parse_node(&graph, &swhid_or_node)?;
                            println!(
                                "{}",
                                serde_json::to_string(&Node {
                                    properties: get_properties(&graph, node)?,
                                    successors: Some(collect_labeled_successors(
                                        &graph,
                                        graph.labeled_successors(node)
                                    )?),
                                    predecessors: Some(collect_labeled_successors(
                                        &graph,
                                        graph.labeled_predecessors(node).into_iter()
                                    )?),
                                    swhid,
                                })
                                .unwrap()
                            );
                        }
                    }
                    Labels::None => {
                        for swhid_or_node in args.nodes {
                            let (node, swhid) = parse_node(&graph, &swhid_or_node)?;
                            println!(
                                "{}",
                                serde_json::to_string(&Node {
                                    properties: get_properties(&graph, node)?,
                                    successors: Some(collect_successors(
                                        &graph,
                                        graph.successors(node)
                                    )?),
                                    predecessors: Some(collect_successors(
                                        &graph,
                                        graph.predecessors(node)
                                    )?),
                                    swhid,
                                })
                                .unwrap()
                            );
                        }
                    }
                }
            }
            Direction::Forward => {
                let graph = SwhUnidirectionalGraph::new(&args.graph_path)
                    .context("Could not load graph")?;
                let graph = load_properties!(graph)?;
                match args.labels {
                    Labels::Bidirectional => {
                        let graph = graph
                            .load_properties(|properties| {
                                properties
                                    .load_label_names()
                                    .context("Could not load label names")
                            })?
                            .load_labels()
                            .context("Could not load labels")?;
                        for swhid_or_node in args.nodes {
                            let (node, swhid) = parse_node(&graph, &swhid_or_node)?;
                            println!(
                                "{}",
                                serde_json::to_string(&Node {
                                    properties: get_properties(&graph, node)?,
                                    successors: Some(collect_labeled_successors(
                                        &graph,
                                        graph.labeled_successors(node)
                                    )?),
                                    predecessors: None,
                                    swhid,
                                })
                                .unwrap()
                            );
                        }
                    }
                    Labels::None => {
                        for swhid_or_node in args.nodes {
                            let (node, swhid) = parse_node(&graph, &swhid_or_node)?;
                            println!(
                                "{}",
                                serde_json::to_string(&Node {
                                    properties: get_properties(&graph, node)?,
                                    successors: Some(collect_successors(
                                        &graph,
                                        graph.successors(node)
                                    )?),
                                    predecessors: None,
                                    swhid,
                                })
                                .unwrap()
                            );
                        }
                    }
                }
            }
        },
        GraphFormat::Json => {
            ensure!(args.direction == Direction::Bidirectional, "--graph-format json and --direction are mutually exclusive (graphs deserialized from JSON are always bidirectional)");
            ensure!(args.labels == Labels::Bidirectional, "--graph-format json and --labels are mutually exclusive (graphs' JSON serialization always contains labels)");

            let file = std::fs::File::open(&args.graph_path)
                .with_context(|| format!("Could not open {}", args.graph_path.display()))?;
            let mut deserializer = serde_json::Deserializer::from_reader(BufReader::new(file));
            let graph: SwhBidirectionalGraph<
                properties::SwhGraphProperties<
                    _,
                    properties::VecTimestamps,
                    properties::VecPersons,
                    properties::VecContents,
                    properties::VecStrings,
                    properties::VecLabelNames,
                >,
                _,
                _,
            > = swh_graph::serde::deserialize_with_labels_and_maps(
                &mut deserializer,
                args.graph_path.clone(),
            )
            .map_err(|e| anyhow!("Could not read JSON graph: {e}"))?;
            for swhid_or_node in args.nodes {
                let (node, swhid) = parse_node(&graph, &swhid_or_node)?;
                println!(
                    "{}",
                    serde_json::to_string(&Node {
                        properties: get_properties(&graph, node)?,
                        successors: Some(collect_labeled_successors(
                            &graph,
                            graph.labeled_successors(node)
                        )?),
                        predecessors: Some(collect_labeled_successors(
                            &graph,
                            graph.labeled_predecessors(node).into_iter()
                        )?),
                        swhid,
                    })
                    .unwrap()
                );
            }
        }
    }

    Ok(())
}

fn parse_node(
    graph: &impl SwhGraphWithProperties<Maps: properties::Maps>,
    swhid_or_node: &str,
) -> Result<(NodeId, SWHID)> {
    Ok(match swhid_or_node.parse() {
        Ok(node) => (
            node,
            graph
                .properties()
                .try_swhid(node)
                .with_context(|| format!("Unknown node id: {node}"))?,
        ),
        Err(_) => {
            let swhid = swhid_or_node.parse()?;
            let node = graph.properties().node_id(swhid)?;
            (node, swhid)
        }
    })
}

#[derive(serde::Serialize)]
struct Node {
    swhid: SWHID,
    properties: Properties,
    successors: Option<Vec<Succ>>,
    predecessors: Option<Vec<Succ>>,
}

#[derive(serde::Serialize)]
struct Succ {
    swhid: SWHID,
    labels: Option<Vec<Label>>,
}

#[derive(serde::Serialize)]
#[serde(untagged)]
enum Label {
    Branch {
        branch_name: String,
    },
    DirEntry {
        file_name: String,
        permission: Option<u16>,
    },
    Visit {
        status: &'static str,
        timestamp: u64,
    },
}

impl Label {
    fn new<G: SwhGraphWithProperties<LabelNames: properties::LabelNames>>(
        graph: G,
        label: EdgeLabel,
    ) -> Result<Self> {
        Ok(match label {
            EdgeLabel::Branch(branch) => Label::Branch {
                branch_name: String::from_utf8_lossy(
                    &graph.properties().label_name(branch.label_name_id()),
                )
                .into_owned(),
            },
            EdgeLabel::DirEntry(entry) => Label::DirEntry {
                file_name: String::from_utf8_lossy(
                    &graph.properties().label_name(entry.label_name_id()),
                )
                .into_owned(),
                permission: entry.permission().map(|perm| perm.to_git()),
            },
            EdgeLabel::Visit(visit) => Label::Visit {
                status: match visit.status() {
                    VisitStatus::Full => "full",
                    VisitStatus::Partial => "partial",
                },
                timestamp: visit.timestamp(),
            },
        })
    }
}

fn collect_labeled_successors<
    G: SwhGraphWithProperties<Maps: properties::Maps, LabelNames: properties::LabelNames>,
>(
    graph: G,
    successors: impl Iterator<Item = (usize, impl Iterator<Item = EdgeLabel>)>,
) -> Result<Vec<Succ>> {
    successors
        .map(|(succ, labels)| -> Result<_> {
            Ok(Succ {
                swhid: graph.properties().swhid(succ),
                labels: Some(
                    labels
                        .map(|label| Label::new(&graph, label))
                        .collect::<Result<_>>()?,
                ),
            })
        })
        .collect()
}

fn collect_successors<G: SwhGraphWithProperties<Maps: properties::Maps>>(
    graph: G,
    successors: impl Iterator<Item = usize>,
) -> Result<Vec<Succ>> {
    successors
        .map(|succ| -> Result<_> {
            Ok(Succ {
                swhid: graph.properties().swhid(succ),
                labels: None,
            })
        })
        .collect()
}

#[derive(Default, serde::Serialize)]
struct Properties {
    // cnt
    length: Option<u64>,
    is_skipped_content: Option<bool>,

    // rev/rel
    author_timestamp: Option<i64>,
    author_timestamp_offset: Option<i16>,
    committer_timestamp: Option<i64>,
    committer_timestamp_offset: Option<i16>,
    author_id: Option<u32>,
    committer_id: Option<u32>,
    tag_name: Option<String>,
    message: Option<String>,

    // ori
    url: Option<String>,
}

fn get_properties<
    G: SwhGraphWithProperties<
        Maps: properties::Maps,
        Timestamps: properties::OptTimestamps,
        Persons: properties::OptPersons,
        Contents: properties::OptContents,
        Strings: properties::OptStrings,
    >,
>(
    graph: G,
    node: usize,
) -> Result<Properties> {
    let mut properties = Properties::default();
    match graph.properties().node_type(node) {
        NodeType::Content => {
            properties.length = map::<G::Contents, _>(graph.properties().content_length(node));
            properties.is_skipped_content = Some(map::<G::Contents, _>(
                graph.properties().is_skipped_content(node),
            ));
        }
        NodeType::Directory => {}
        NodeType::Revision => {
            properties.author_timestamp =
                map::<G::Timestamps, _>(graph.properties().author_timestamp(node));
            properties.author_timestamp_offset =
                map::<G::Timestamps, _>(graph.properties().author_timestamp_offset(node));
            properties.committer_timestamp =
                map::<G::Timestamps, _>(graph.properties().committer_timestamp(node));
            properties.committer_timestamp_offset =
                map::<G::Timestamps, _>(graph.properties().committer_timestamp_offset(node));
            properties.author_id = map::<G::Persons, _>(graph.properties().author_id(node));
            properties.committer_id = map::<G::Persons, _>(graph.properties().committer_id(node));
            properties.message = map::<G::Strings, _>(graph.properties().message(node))
                .map(|url| String::from_utf8_lossy(&url).into_owned());
        }
        NodeType::Release => {
            properties.author_timestamp =
                map::<G::Timestamps, _>(graph.properties().author_timestamp(node));
            properties.author_timestamp_offset =
                map::<G::Timestamps, _>(graph.properties().author_timestamp_offset(node));
            properties.author_id = map::<G::Persons, _>(graph.properties().author_id(node));
            properties.tag_name = map::<G::Strings, _>(graph.properties().tag_name(node))
                .map(|tag_name| String::from_utf8_lossy(&tag_name).into_owned());
            properties.message = map::<G::Strings, _>(graph.properties().message(node))
                .map(|message| String::from_utf8_lossy(&message).into_owned());
        }
        NodeType::Snapshot => {}
        NodeType::Origin => {
            properties.url = map::<G::Strings, _>(graph.properties().message(node))
                .map(|url| String::from_utf8_lossy(&url).into_owned());
        }
    }

    Ok(properties)
}

fn map<PB: properties::PropertiesBackend, T: Default>(
    value: <PB::DataFilesAvailability as properties::DataFilesAvailability>::Result<'_, T>,
) -> T {
    use swh_graph::properties::DataFilesAvailability;

    PB::DataFilesAvailability::make_result(value).unwrap_or_default()
}