craftql 0.2.20

A CLI tool to visualize GraphQL schemas and to output a graph data structure as a graphviz .dot format
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
use crate::{
    config::ALLOWED_EXTENSIONS,
    extend_types::ExtendType,
    state::{Entity, GraphQL, GraphQLType, Node},
};

use anyhow::Result;
use async_std::{
    fs,
    future::Future,
    path::{Path, PathBuf},
    pin::Pin,
    prelude::*,
    sync::{Arc, Mutex},
};
use graphql_parser::{parse_schema, schema};
use petgraph::{graph::NodeIndex, Direction};
use std::{collections::HashMap, process::exit};

/// Check if a file extension is allowed.
fn is_extension_allowed(extension: &str) -> bool {
    ALLOWED_EXTENSIONS.to_vec().contains(&extension)
}

/// Print missing definitions.
pub async fn print_missing_definitions(
    graph: Arc<Mutex<petgraph::Graph<Node, (NodeIndex, NodeIndex)>>>,
    missing_definitions: Arc<Mutex<HashMap<NodeIndex, Vec<String>>>>,
) -> Result<()> {
    let graph = graph.lock().await;
    let missing_definitions = missing_definitions.lock().await;

    for (node_index, definitions) in missing_definitions.iter() {
        println!(
            "\n# {} {} not defined in:{}",
            definitions.join(", "),
            if definitions.len() == 1 { "is" } else { "are" },
            graph.node_weight(*node_index).unwrap().entity,
        );
    }

    Ok(())
}

/// Find and return neighbors of a node.
pub async fn find_neighbors(
    node: &str,
    graph: Arc<Mutex<petgraph::Graph<Node, (NodeIndex, NodeIndex)>>>,
    direction: Direction,
) -> Vec<Entity> {
    let graph = graph.lock().await;

    match graph.node_indices().find(|index| graph[*index].id == node) {
        Some(index) => graph
            .neighbors_directed(index, direction)
            .map(|index| &graph.node_weight(index).unwrap().entity)
            .cloned()
            .collect::<Vec<Entity>>(),
        None => vec![],
    }
}

/// Print orphan nodes.
pub async fn find_and_print_neighbors(
    node: &str,
    graph: Arc<Mutex<petgraph::Graph<Node, (NodeIndex, NodeIndex)>>>,
    direction: Direction,
) -> Result<()> {
    let graph_clone = graph.clone();

    // Ensure that the node exists!
    find_node(node, graph).await?;

    let dependencies = find_neighbors(node, graph_clone, direction).await;

    if dependencies.is_empty() {
        eprintln!("No dependencies found for node {}", node);
        exit(1);
    }

    for dependency in dependencies {
        println!("{}", dependency);
    }

    Ok(())
}

/// Find and return orphan nodes.
pub async fn find_orphans(
    graph: Arc<Mutex<petgraph::Graph<Node, (NodeIndex, NodeIndex)>>>,
) -> Vec<Entity> {
    let graph = &graph.lock().await;
    let externals = graph.externals(Direction::Outgoing);
    let has_root_schema = graph
        .node_indices()
        .any(|index| graph[index].id == "schema");

    externals
        .filter_map(|index| {
            let entity = graph.node_weight(index).unwrap().entity.clone();

            match entity.graphql {
                // Skip root schema has it can't have outgoing edges.
                GraphQL::Schema => None,
                // Skip Mutation, Query and Subscription if no root schema is defined
                // as those nodes can't have outgoing edges.
                GraphQL::TypeDefinition(GraphQLType::Object)
                    if (!has_root_schema
                        && (entity.name == "Mutation"
                            || entity.name == "Query"
                            || entity.name == "Subscription")) =>
                {
                    None
                }
                _ => Some(entity),
            }
        })
        .collect::<Vec<Entity>>()
}

/// Print orphan nodes.
pub async fn find_and_print_orphans(
    graph: Arc<Mutex<petgraph::Graph<Node, (NodeIndex, NodeIndex)>>>,
) -> Result<()> {
    let orphans = find_orphans(graph).await;

    if orphans.is_empty() {
        eprintln!("No orphan node found");
        exit(1);
    }

    for orphan in orphans {
        println!("{}", orphan);
    }

    Ok(())
}

/// Find a node by name, display it with syntax highlighting or exit.
pub async fn find_node(
    node: &str,
    graph: Arc<Mutex<petgraph::Graph<Node, (NodeIndex, NodeIndex)>>>,
) -> Result<()> {
    let graph = graph.lock().await;

    match graph.node_indices().find(|index| graph[*index].id == node) {
        Some(index) => {
            let entity = &graph.node_weight(index).unwrap().entity;

            println!("{}", entity);

            Ok(())
        }
        None => {
            eprintln!("Node {} not found", node);
            exit(1);
        }
    }
}

/// Recursively read directories and files for a given path.
pub fn get_files(
    path: PathBuf,
    files: Arc<Mutex<HashMap<PathBuf, String>>>,
) -> Pin<Box<dyn Future<Output = Result<()>>>> {
    // Use a hack to get async recursive calls working.
    Box::pin(async move {
        let thread_safe_path = Arc::new(path);
        let file_or_dir = fs::metadata(thread_safe_path.as_ref()).await?;
        let file_type = file_or_dir.file_type();
        let extension = match Path::new(thread_safe_path.as_ref()).extension() {
            Some(extension) => extension.to_str().unwrap(),
            None => "",
        };

        if file_type.is_file() {
            if is_extension_allowed(extension) {
                let contents = fs::read_to_string(thread_safe_path.as_ref()).await?;
                let mut files = files.lock().await;

                files.insert(thread_safe_path.as_ref().clone(), contents);
            }

            return Ok(());
        }

        let mut dir = fs::read_dir(thread_safe_path.as_ref()).await?;

        while let Some(result) = dir.next().await {
            let entry: fs::DirEntry = result?;
            let inner_path = entry.path();
            let inner_path_cloned = inner_path.clone();
            let metadata = entry.clone().metadata().await?;
            let is_dir = metadata.is_dir();
            let extension = match &inner_path.extension() {
                Some(extension) => extension.to_str().unwrap(),
                None => "",
            };

            if !is_dir && is_extension_allowed(extension) {
                let contents = fs::read_to_string(inner_path).await?;
                let mut files = files.lock().await;

                files.insert(inner_path_cloned, contents);
            } else {
                get_files(inner_path, files.clone()).await?;
            }
        }

        Ok(())
    })
}

async fn add_node_and_dependencies(
    entity: impl ExtendType,
    filter: &[GraphQL],
    graph: Arc<Mutex<petgraph::Graph<Node, (NodeIndex, NodeIndex)>>>,
    dependencies: Arc<Mutex<HashMap<NodeIndex, Vec<String>>>>,
    file: &(PathBuf, String),
) -> Result<()> {
    // If a filter is provided and the mapped type of the entity is not part of
    // this filter, skip it.
    if !filter.is_empty() && !filter.to_vec().contains(&entity.get_mapped_type()) {
        return Ok(());
    }

    let mut graph = graph.lock().await;

    let entity_dependencies = entity.get_dependencies();
    let (id, name) = entity.get_id_and_name();
    let new_entity = Entity::new(
        entity_dependencies.clone(),
        entity.get_mapped_type(),
        id,
        name,
        file.0.to_owned(),
        entity.get_raw(),
    );
    let node_id = new_entity.id.clone();
    let node_index = graph.add_node(Node::new(new_entity, node_id));

    // Update dependencies.
    let mut dependencies = dependencies.lock().await;
    dependencies.insert(node_index, entity_dependencies);

    Ok(())
}

/// Parse the files, generate an AST and walk it to populate the graph.
pub async fn populate_graph_from_ast(
    dependencies: Arc<Mutex<HashMap<NodeIndex, Vec<String>>>>,
    files: Arc<Mutex<HashMap<PathBuf, String>>>,
    filter: &[GraphQL],
    graph: Arc<Mutex<petgraph::Graph<Node, (NodeIndex, NodeIndex)>>>,
    missing_definitions: Arc<Mutex<HashMap<NodeIndex, Vec<String>>>>,
) -> Result<()> {
    let files = files.lock().await;

    // Populate the nodes first.
    for file in files.clone() {
        let ast = parse_schema::<String>(file.1.as_str())?;

        // Reference: http://spec.graphql.org/draft/
        for definition in ast.definitions {
            let graph = graph.clone();
            let dependencies = dependencies.clone();

            match definition {
                schema::Definition::TypeDefinition(type_definition) => {
                    add_node_and_dependencies(type_definition, filter, graph, dependencies, &file)
                        .await?
                }
                schema::Definition::TypeExtension(type_extension) => {
                    add_node_and_dependencies(type_extension, filter, graph, dependencies, &file)
                        .await?
                }
                schema::Definition::SchemaDefinition(schema_definition) => {
                    add_node_and_dependencies(schema_definition, filter, graph, dependencies, &file)
                        .await?
                }
                schema::Definition::DirectiveDefinition(directive_definition) => {
                    add_node_and_dependencies(
                        directive_definition,
                        filter,
                        graph,
                        dependencies,
                        &file,
                    )
                    .await?
                }
            }
        }
    }

    // Populate the edges.
    let dependencies = &*dependencies.lock().await;

    for (node_index, inner_dependencies) in dependencies {
        let mut node_missing_definitions: Vec<String> = vec![];

        for dependency in inner_dependencies {
            let mut graph = graph.lock().await;

            match graph
                .node_indices()
                .find(|index| graph[*index].id == *dependency)
            {
                Some(index) => match &graph[*node_index].entity.graphql {
                    // Reverse edge for extension types.
                    GraphQL::TypeExtension(GraphQLType::Enum)
                    | GraphQL::TypeExtension(GraphQLType::InputObject)
                    | GraphQL::TypeExtension(GraphQLType::Interface)
                    | GraphQL::TypeExtension(GraphQLType::Object)
                    | GraphQL::TypeExtension(GraphQLType::Scalar)
                    | GraphQL::TypeExtension(GraphQLType::Union) => {
                        graph.update_edge(*node_index, index, (*node_index, index));
                    }
                    _ => {
                        graph.update_edge(index, *node_index, (index, *node_index));
                    }
                },
                None => match dependency.as_str() {
                    // Built-in Scalars, skip.
                    "Boolean" | "Float" | "ID" | "Int" | "String" => {}
                    // Keep track of possible missing definitions, should have been resolved at this point!
                    _ => {
                        node_missing_definitions.push(dependency.to_owned());
                    }
                },
            }
        }

        if !node_missing_definitions.is_empty() {
            missing_definitions
                .lock()
                .await
                .insert(*node_index, node_missing_definitions);
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::state::{Data, GraphQL, GraphQLType, State};

    use async_std::task;
    use petgraph::graph::NodeIndex;

    async fn scaffold(files: Vec<(PathBuf, String)>, filters: &[GraphQL]) -> Data {
        let state = State::new();
        let shared_data = state.shared;
        let shared_data_for_populate = shared_data.clone();

        task::block_on(async {
            let mut shared_files = shared_data.files.lock().await;

            for (path, contents) in files {
                shared_files.insert(path, contents);
            }
        });

        populate_graph_from_ast(
            shared_data_for_populate.dependencies,
            shared_data_for_populate.files,
            filters,
            shared_data_for_populate.graph,
            shared_data_for_populate.missing_definitions,
        )
        .await
        .unwrap();

        shared_data
    }

    #[async_std::test]
    async fn check_dependencies_and_graph() {
        let house_contents = "type House { price: Int! rooms: Int! @test owner: Owner! }";
        let house_dependencies = vec!["@test", "Int", "Owner"];
        let house_name = "House";
        let house_path = "some_path/House.gql";

        let owner_contents = "type Owner { name: String! }";
        let owner_dependencies = vec!["String"];
        let owner_name = "Owner";
        let owner_path = "some_path/Owner.graphql";

        let shared_data = scaffold(
            vec![
                (PathBuf::from(house_path), String::from(house_contents)),
                (PathBuf::from(owner_path), String::from(owner_contents)),
            ],
            &[],
        )
        .await;

        let dependencies = shared_data.dependencies.lock().await;

        assert_eq!(dependencies.len(), 2);

        // There no determined insertion order, assign dependencies lists based
        // on respective assumed lengths.
        let (current_owner_dependencies, current_house_dependencies, is_same_order) =
            if dependencies.get(&NodeIndex::new(0)).unwrap().len() == house_dependencies.len() {
                (
                    dependencies.get(&NodeIndex::new(1)).unwrap(),
                    dependencies.get(&NodeIndex::new(0)).unwrap(),
                    true,
                )
            } else {
                (
                    dependencies.get(&NodeIndex::new(0)).unwrap(),
                    dependencies.get(&NodeIndex::new(1)).unwrap(),
                    false,
                )
            };

        // List of dependencies should match.
        assert_eq!(current_owner_dependencies, &owner_dependencies);
        assert_eq!(current_house_dependencies, &house_dependencies);

        // Graph should contains 2 nodes and 1 edge.
        let graph = shared_data.graph.lock().await;
        assert_eq!(graph.node_count(), 2);
        assert_eq!(graph.edge_count(), 1);

        // Check house.
        let house_node_index = if is_same_order {
            NodeIndex::new(0)
        } else {
            NodeIndex::new(1)
        };
        let house = graph.node_weight(house_node_index).unwrap();
        assert_eq!(house.id, String::from(house_name));
        assert_eq!(house.entity.dependencies, house_dependencies);
        assert_eq!(
            house.entity.graphql,
            GraphQL::TypeDefinition(GraphQLType::Object)
        );
        assert_eq!(house.entity.id, String::from(house_name));
        assert_eq!(house.entity.name, String::from(house_name));
        assert_eq!(house.entity.path, PathBuf::from(house_path));
        // We need to parse and format the AST in order to get the same output!
        assert_eq!(
            house.entity.raw.to_string(),
            format!(
                "{}",
                parse_schema::<String>(house_contents).unwrap().to_owned()
            )
        );

        // Check owner.
        let owner_node_index = if is_same_order {
            NodeIndex::new(1)
        } else {
            NodeIndex::new(0)
        };
        let owner = graph.node_weight(owner_node_index).unwrap();
        assert_eq!(owner.id, String::from(owner_name));
        assert_eq!(owner.entity.dependencies, owner_dependencies);
        assert_eq!(
            owner.entity.graphql,
            GraphQL::TypeDefinition(GraphQLType::Object)
        );
        assert_eq!(owner.entity.id, String::from(owner_name));
        assert_eq!(owner.entity.name, String::from(owner_name));
        assert_eq!(owner.entity.path, PathBuf::from(owner_path));
        // We need to parse and format the AST in order to get the same output!
        assert_eq!(
            owner.entity.raw.to_string(),
            format!(
                "{}",
                parse_schema::<String>(owner_contents).unwrap().to_owned()
            )
        );

        // Check the edges. Owner should be directed to House, not the other
        // way around!
        assert!(graph.contains_edge(owner_node_index, house_node_index));
        assert!(!graph.contains_edge(house_node_index, owner_node_index));
    }

    #[async_std::test]
    async fn check_orphans() {
        let shared_data = scaffold(
            vec![(
                PathBuf::from("some_path/Peer.gql"),
                String::from("type Peer { id: String! }"),
            )],
            &[],
        )
        .await;

        task::block_on(async {
            let graph = shared_data.graph.lock().await;
            assert_eq!(graph.node_count(), 1);
            assert_eq!(graph.edge_count(), 0);
        });

        assert_eq!(find_orphans(shared_data.graph).await.len(), 1);
    }

    #[async_std::test]
    async fn check_orphans_with_schema() {
        let shared_data = scaffold(
            vec![(
                PathBuf::from("some_path/Schema.gql"),
                String::from("schema { query: Query }"),
            )],
            &[],
        )
        .await;

        task::block_on(async {
            let graph = shared_data.graph.lock().await;
            assert_eq!(graph.node_count(), 1);
            assert_eq!(graph.edge_count(), 0);
        });

        assert_eq!(find_orphans(shared_data.graph).await.len(), 0);
    }

    #[async_std::test]
    async fn check_orphans_without_schema_but_with_query_mutation_subscription() {
        let shared_data = scaffold(
            vec![
                (
                    PathBuf::from("some_path/Query.gql"),
                    String::from("type Query { foo(bar: String): String }"),
                ),
                (
                    PathBuf::from("some_path/Mutation.gql"),
                    String::from("type Mutation { foo(bar: String): String }"),
                ),
                (
                    PathBuf::from("some_path/Subscription.gql"),
                    String::from("type Subscription { foo(bar: String): String }"),
                ),
            ],
            &[],
        )
        .await;

        task::block_on(async {
            let graph = shared_data.graph.lock().await;
            assert_eq!(graph.node_count(), 3);
            assert_eq!(graph.edge_count(), 0);
        });

        assert_eq!(find_orphans(shared_data.graph).await.len(), 0);
    }

    #[async_std::test]
    async fn check_neighbors() {
        let shared_data = scaffold(
            vec![
                (
                    PathBuf::from("some_path/Foo.gql"),
                    String::from("type Foo { field: Bar }"),
                ),
                (
                    PathBuf::from("some_path/Bar.gql"),
                    String::from("interface Bar { id: ID!}"),
                ),
            ],
            &[],
        )
        .await;

        task::block_on(async {
            let graph = shared_data.graph.lock().await;
            assert_eq!(graph.node_count(), 2);
            assert_eq!(graph.edge_count(), 1);
        });

        // Foo depends on Bar but is not a dependency.
        let incoming = find_neighbors("Foo", shared_data.graph.clone(), Direction::Incoming).await;
        let outgoing = find_neighbors("Foo", shared_data.graph.clone(), Direction::Outgoing).await;

        assert_eq!(incoming.len(), 1);
        assert_eq!(incoming.first().unwrap().name, "Bar");
        assert_eq!(outgoing.len(), 0);

        // Bar depends on nothing but is a dependency of Foo.
        let incoming = find_neighbors("Bar", shared_data.graph.clone(), Direction::Incoming).await;
        let outgoing = find_neighbors("Bar", shared_data.graph.clone(), Direction::Outgoing).await;

        assert_eq!(incoming.len(), 0);
        assert_eq!(outgoing.len(), 1);
        assert_eq!(outgoing.first().unwrap().name, "Foo");
    }

    #[async_std::test]
    async fn check_missing_definitions() {
        let shared_data = scaffold(
            vec![
                (
                    PathBuf::from("some_path/Foo.gql"),
                    String::from("type Foo { field: Woot, otherField: Why }"),
                ),
                (
                    PathBuf::from("some_path/Bar.gql"),
                    String::from("interface Bar { id: What!}"),
                ),
            ],
            &[],
        )
        .await;

        let graph = shared_data.graph.lock().await;
        assert_eq!(graph.node_count(), 2);
        assert_eq!(graph.edge_count(), 0);

        let missing_definitions = shared_data.missing_definitions.lock().await;

        let (bar_missing_dependencies, foo_missing_dependencies) =
            if missing_definitions.get(&NodeIndex::new(0)).unwrap().len() == 2 {
                (
                    missing_definitions.get(&NodeIndex::new(1)).unwrap(),
                    missing_definitions.get(&NodeIndex::new(0)).unwrap(),
                )
            } else {
                (
                    missing_definitions.get(&NodeIndex::new(0)).unwrap(),
                    missing_definitions.get(&NodeIndex::new(1)).unwrap(),
                )
            };

        assert_eq!(
            *foo_missing_dependencies,
            vec![String::from("Why"), String::from("Woot")]
        );
        assert_eq!(*bar_missing_dependencies, vec![String::from("What")]);
    }

    #[async_std::test]
    async fn check_filtering() {
        let shared_data = scaffold(
            vec![
                (
                    PathBuf::from("some_path/Foo.gql"),
                    String::from("type Foo { a: ID! }"),
                ),
                (
                    PathBuf::from("some_path/Bar.gql"),
                    String::from("interface Bar { b: ID! }"),
                ),
                (
                    PathBuf::from("some_path/Cow.gql"),
                    String::from("input Cow { c: ID! }"),
                ),
            ],
            &[
                GraphQL::TypeDefinition(GraphQLType::Object),
                GraphQL::TypeDefinition(GraphQLType::InputObject),
            ],
        )
        .await;

        let graph = shared_data.graph.lock().await;
        assert_eq!(graph.node_count(), 2);
        assert_eq!(graph.edge_count(), 0);

        let mut selected_entities = graph
            .node_indices()
            .map(|index| &graph.node_weight(index).unwrap().id)
            .collect::<Vec<&String>>();
        // Sort the entities as the order is not as there no determined insertion order.
        selected_entities.sort();
        assert_eq!(selected_entities, vec!["Cow", "Foo"]);
    }
}