---
title: "Dependency Graph"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Dependency Graph}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r setup, echo=FALSE, }
library(ghactions4r)
```

## Dependency graph

GitHub provides a dependency graph that shows the dependencies and dependents of the `ghactions4r` package. The figure below helps visualize the GitHub repos that are dependents of the `ghactions4r` GitHub Actions workflows.

```{r, echo=FALSE, warning=FALSE, message=FALSE, results=FALSE}
library(visNetwork)
library(rvest)
library(dplyr)
```

```{r, echo=FALSE, warning=FALSE, message=FALSE, fig.height=10, fig.width=10}
# Download data from GitHub dependency graph page
webpage <- rvest::read_html(
  x = "https://github.com/nmfs-fish-tools/ghactions4r/network/dependents"
)

# Extract yml ID links
gha_links <- webpage %>%
  rvest::html_nodes("details-menu") %>%
  rvest::html_nodes(".select-menu-item") %>%
  rvest::html_attr("href")

# Extract yml name data
gha_names <- webpage %>%
  rvest::html_nodes("details-menu") %>%
  rvest::html_nodes(".select-menu-item-text") %>%
  rvest::html_text()

gha_names <- sapply(1:length(gha_names), function(x) gsub("[\r\n]", "/", gha_names[x]))
gha_names <- sapply(1:length(gha_names), function(x) strsplit(gha_names[x], "/")[[1]][6])

# Extract dependents data for each yml file
gha_data <- list()
for (i in 1:length(gha_names)) {
  webpage <- rvest::read_html(
    x = paste0("https://github.com", gha_links[i])
  )

  gha_data[[i]] <- webpage %>%
    rvest::html_nodes(".Box-row") %>%
    rvest::html_nodes("span") %>%
    rvest::html_nodes(".text-bold") %>%
    rvest::html_attr("href")
}
names(gha_data) <- gha_names

# Prepare data to plot dependency graph
dep_data <- list()
dep_label <- c(gha_names, unique(unlist(gha_data)))
dep_data$Nomfun <- data.frame(
  id = 1:length(dep_label),
  label = dep_label
)

dep_data$fromto <- data.frame(
  from = NA,
  to = NA
)
for (i in 1:length(gha_data)) {
  for (j in 1:length(gha_data[[i]])) {
    from_id <- dep_data$Nomfun$id[dep_data$Nomfun$label == names(gha_data)[i]]
    to_id <- dep_data$Nomfun$id[dep_data$Nomfun$label == gha_data[[i]][j]]
    dep_data$fromto <- rbind(dep_data$fromto, c(from_id, to_id))
  }
}

visNetwork::visNetwork(dep_data$Nomfun, dep_data$fromto, width = "100%")
```
