Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(docs): use variables for docs.rs links #1098

Merged
merged 31 commits into from
Oct 5, 2023
Merged
Show file tree
Hide file tree
Changes from 29 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
06c95f3
chore(docs): use variables for docs.rs links
Br1ght0ne Aug 21, 2023
4d38507
fix(ci): add mdbook-variables to gh-pages workflow
Br1ght0ne Aug 21, 2023
f770242
docs: mention mdbook-variables in README.md
Br1ght0ne Aug 21, 2023
f3845e5
docs: use fuels_types name (with underscore)
Br1ght0ne Aug 22, 2023
0971a18
docs: shorten fuels version to just MAJOR.MINOR
Br1ght0ne Aug 22, 2023
151a511
docs: replace fuels version in getting-started.md
Br1ght0ne Aug 22, 2023
9518df9
scripts: add version replacer script
Br1ght0ne Aug 31, 2023
91b8e45
docs: remove mdbook-variables mentions
Br1ght0ne Aug 31, 2023
0b70126
Merge branch 'master' into oleksii/mdbook-versions
Br1ght0ne Aug 31, 2023
d8d9092
change to test branch of docs action
Br1ght0ne Aug 31, 2023
7479a7b
ci: add pre-command input to docs.yml
Br1ght0ne Aug 31, 2023
9f6277b
count replacements, overwrite files on change only
Br1ght0ne Sep 1, 2023
5ccdbee
add unit tests
Br1ght0ne Sep 1, 2023
40b16b0
normalize test code
Br1ght0ne Sep 1, 2023
df719e5
Use master branch of docs workflow
Br1ght0ne Sep 1, 2023
8829afe
Merge branch 'master' into oleksii/mdbook-versions
Br1ght0ne Sep 1, 2023
331f45a
Merge branch 'master' into oleksii/mdbook-versions
Br1ght0ne Sep 5, 2023
4660c62
Merge branch 'master' into oleksii/mdbook-versions
hal3e Sep 6, 2023
664422b
Apply suggestions from code review
Br1ght0ne Sep 7, 2023
9a306f3
use 0 instead of None for "no replacements"
Br1ght0ne Sep 7, 2023
4c7f606
cargo fmt
Br1ght0ne Sep 7, 2023
53ebf5c
Remove `external-versions` metadata table
Br1ght0ne Sep 7, 2023
2beb80f
Merge branch 'master' into oleksii/mdbook-versions
Br1ght0ne Sep 9, 2023
6a6484d
Merge branch 'master' into oleksii/mdbook-versions
Br1ght0ne Sep 25, 2023
718e50c
Merge branch 'master' into oleksii/mdbook-versions
Br1ght0ne Sep 27, 2023
44f7603
remove unused serde_json dependency
Br1ght0ne Sep 27, 2023
a0960fc
Merge branch 'master' into oleksii/mdbook-versions
Br1ght0ne Sep 27, 2023
da941b2
Merge branch 'master' into oleksii/mdbook-versions
Br1ght0ne Sep 28, 2023
3a3229a
Merge branch 'master' into oleksii/mdbook-versions
hal3e Sep 29, 2023
0a7c9cb
Merge branch 'master' into oleksii/mdbook-versions
Br1ght0ne Oct 4, 2023
f9d8a2b
Merge branch 'master' into oleksii/mdbook-versions
hal3e Oct 5, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ jobs:
test:
uses: FuelLabs/github-actions/.github/workflows/mdbook-docs.yml@master
with:
docs-src-path: 'docs/src'

docs-src-path: "docs/src"
pre-command: 'cargo run --package versions-replacer -- ./docs --manifest-path ./Cargo.toml --filename-regex "\.md$"'
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ members = [
"packages/fuels-test-helpers",
"packages/wasm-tests",
"scripts/check-docs",
"scripts/versions-replacer",
]

[workspace.package]
Expand Down
2 changes: 1 addition & 1 deletion docs/src/calling-contracts/call-params.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ The parameters for a contract call are:
3. Gas forwarded
<!-- call_params:example:end -->

You can use these to forward coins to a contract. You can configure these parameters by creating an instance of [`CallParameters`](https://docs.rs/fuels/latest/fuels/programs/contract/struct.CallParameters.html) and passing it to a chain method called `call_params`.
You can use these to forward coins to a contract. You can configure these parameters by creating an instance of [`CallParameters`](https://docs.rs/fuels/{{versions.fuels}}/fuels/programs/contract/struct.CallParameters.html) and passing it to a chain method called `call_params`.
<!-- use_call_params:example:end -->

For instance, suppose the following contract that uses Sway's `msg_amount()` to return the amount sent in that transaction.
Expand Down
2 changes: 1 addition & 1 deletion docs/src/connecting/querying.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Querying the blockchain

Once you set up a provider, you can interact with the Fuel blockchain. Here are a few examples of what you can do with a provider; for a more in-depth overview of the API, check the [official provider API documentation](https://docs.rs/fuels/latest/fuels/accounts/provider/struct.Provider.html).
Once you set up a provider, you can interact with the Fuel blockchain. Here are a few examples of what you can do with a provider; for a more in-depth overview of the API, check the [official provider API documentation](https://docs.rs/fuels/{{versions.fuels}}/fuels/accounts/provider/struct.Provider.html).

- [Set up](#set-up)
- [Get all coins from an address](#get-all-coins-from-an-address)
Expand Down
4 changes: 2 additions & 2 deletions docs/src/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,10 @@ cargo test -- --nocapture
Add these dependencies on your `Cargo.toml`:

```toml
fuels = "0.48"
fuels = "{{versions.fuels}}"
```

> **Note** We're using version `0.48` of the SDK, which is the latest version at the time of this writing.
> **Note** We're using version `{{versions.fuels}}` of the SDK, which is the latest version at the time of this writing.

And then, in your Rust file that's going to make use of the SDK:

Expand Down
2 changes: 1 addition & 1 deletion docs/src/reference.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# API Reference

For a more in-depth look at the APIs provided by the Fuel Rust SDK, head over to the [official documentation](https://docs.rs/fuels/latest/fuels/). In the actual Rust docs, you can see the most up-to-date information about the API, which is synced with the code as it changes.
For a more in-depth look at the APIs provided by the Fuel Rust SDK, head over to the [official documentation](https://docs.rs/fuels/{{versions.fuels}}/fuels/). In the actual Rust docs, you can see the most up-to-date information about the API, which is synced with the code as it changes.
2 changes: 1 addition & 1 deletion docs/src/types/address.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Address

Like `Bytes32`, `Address` is a wrapper on `[u8; 32]` with similar methods and implements the same traits (see [fuel-types documentation](https://docs.rs/fuel-types/latest/fuel_types/struct.Address.html)).
Like `Bytes32`, `Address` is a wrapper on `[u8; 32]` with similar methods and implements the same traits (see [fuel-types documentation](https://docs.rs/fuel-types/{{versions.fuel-types}}/fuel_types/struct.Address.html)).

These are the main ways of creating an `Address`:

Expand Down
2 changes: 1 addition & 1 deletion docs/src/types/asset-id.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# AssetId

Like `Bytes32`, `AssetId` is a wrapper on `[u8; 32]` with similar methods and implements the same traits (see [fuel-types documentation](https://docs.rs/fuel-types/latest/fuel_types/struct.AssetId.html)).
Like `Bytes32`, `AssetId` is a wrapper on `[u8; 32]` with similar methods and implements the same traits (see [fuel-types documentation](https://docs.rs/fuel-types/{{versions.fuel-types}}/fuel_types/struct.AssetId.html)).

These are the main ways of creating an `AssetId`:

Expand Down
2 changes: 1 addition & 1 deletion docs/src/types/bytes32.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ These are the main ways of creating a `Bytes32`:
{{#include ../../../examples/types/src/lib.rs:bytes32_format}}
```

For a full list of implemented methods and traits, see the [fuel-types documentation](https://docs.rs/fuel-types/latest/fuel_types/struct.Bytes32.html).
For a full list of implemented methods and traits, see the [fuel-types documentation](https://docs.rs/fuel-types/{{versions.fuel-types}}/fuel_types/struct.Bytes32.html).

> **Note:** In Fuel, there's a special type called `b256`, which is similar to `Bytes32`; also used to represent hashes, and it holds a 256-bit value. In Rust, through the SDK, this is represented as `Bits256(value)` where `value` is a `[u8; 32]`. If your contract method takes a `b256` as input, all you need to do is pass a `Bits256([u8; 32])` when calling it from the SDK.
2 changes: 1 addition & 1 deletion docs/src/types/contract-id.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# ContractId

Like `Bytes32`, `ContractId` is a wrapper on `[u8; 32]` with similar methods and implements the same traits (see [fuel-types documentation](https://docs.rs/fuel-types/latest/fuel_types/struct.ContractId.html)).
Like `Bytes32`, `ContractId` is a wrapper on `[u8; 32]` with similar methods and implements the same traits (see [fuel-types documentation](https://docs.rs/fuel-types/{{versions.fuel-types}}/fuel_types/struct.ContractId.html)).

These are the main ways of creating a `ContractId`:

Expand Down
20 changes: 20 additions & 0 deletions scripts/versions-replacer/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
name = "versions-replacer"
publish = false
authors.workspace = true
edition.workspace = true
homepage.workspace = true
readme.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
version.workspace = true

[dependencies]
argh = "0.1.12"
cargo_metadata = "0.17.0"
color-eyre = "0.6.2"
once_cell = "1.18.0"
regex = { workspace = true }
serde = { workspace = true, features = ["derive"] }
walkdir = "2.3.3"
2 changes: 2 additions & 0 deletions scripts/versions-replacer/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod metadata;
pub mod replace;
66 changes: 66 additions & 0 deletions scripts/versions-replacer/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
use std::path::PathBuf;

use argh::FromArgs;
use color_eyre::{
eyre::{eyre, Context},
Result,
};
use regex::Regex;
use walkdir::WalkDir;

use versions_replacer::{
metadata::collect_versions_from_cargo_toml, replace::replace_versions_in_file,
};

#[derive(FromArgs)]
/// Replace variables like '{{{{versions.fuels}}}}' with correct versions from Cargo.toml.
/// Uses versions from '[workspace.members]' and '[workspace.metadata.versions-replacer.external-versions]'.
struct VersionsReplacer {
/// path to directory with files containing variables
#[argh(positional)]
path: PathBuf,
/// path to Cargo.toml with versions
#[argh(option)]
manifest_path: PathBuf,
/// regex to filter filenames (example: "\.md$")
#[argh(option)]
filename_regex: Option<Regex>,
}

fn main() -> Result<()> {
let args: VersionsReplacer = argh::from_env();
let versions = collect_versions_from_cargo_toml(&args.manifest_path)?;

let mut total_replacements: Vec<usize> = Vec::new();

for entry in WalkDir::new(&args.path) {
let entry = entry.wrap_err("failed to get directory entry")?;

if entry.path().is_file() {
if let Some(filename_regex) = &args.filename_regex {
Br1ght0ne marked this conversation as resolved.
Show resolved Hide resolved
let file_name = entry
.path()
.file_name()
.ok_or_else(|| eyre!("{:?} has an invalid file name", entry.path()))?
.to_str()
.ok_or_else(|| eyre!("filename is not valid UTF-8"))?;
if !filename_regex.is_match(file_name) {
continue;
}
}

let replacement_count = replace_versions_in_file(entry.path(), &versions)
.wrap_err_with(|| format!("failed to replace versions in {:?}", entry.path()))?;
if replacement_count > 0 {
total_replacements.push(replacement_count);
}
}
}

println!(
"replaced {} variables across {} files",
total_replacements.iter().sum::<usize>(),
total_replacements.len()
);
Ok(())
}
Br1ght0ne marked this conversation as resolved.
Show resolved Hide resolved
32 changes: 32 additions & 0 deletions scripts/versions-replacer/src/metadata.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use std::{collections::HashMap, path::Path};

use cargo_metadata::MetadataCommand;
use color_eyre::{eyre::Context, Result};
use serde::Deserialize;

#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct WorkspaceMetadata {
pub versions_replacer: VersionsReplacerMetadata,
}

#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct VersionsReplacerMetadata {
pub external_versions: HashMap<String, String>,
}

pub fn collect_versions_from_cargo_toml(
manifest_path: impl AsRef<Path>,
) -> Result<HashMap<String, String>> {
let metadata = MetadataCommand::new()
.manifest_path(manifest_path.as_ref())
.exec()
.wrap_err("failed to execute 'cargo metadata'")?;
let version_map = metadata
.packages
.iter()
.map(|package| (package.name.clone(), package.version.to_string()))
.collect::<HashMap<_, _>>();
Ok(version_map)
}
86 changes: 86 additions & 0 deletions scripts/versions-replacer/src/replace.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
use std::{borrow::Cow, collections::HashMap, fs, path::Path};

use color_eyre::{eyre::Context, Result};
use once_cell::sync::Lazy;
use regex::{Captures, Regex};

pub static VERSIONS_REGEX: Lazy<Regex> =
Lazy::new(|| Regex::new(r"\{\{versions\.([\w_-]+)\}\}").unwrap());

pub fn replace_versions_in_file(
path: impl AsRef<Path>,
versions: &HashMap<String, String>,
) -> Result<usize> {
let path = path.as_ref();
let contents =
fs::read_to_string(path).wrap_err_with(|| format!("failed to read {:?}", path))?;
let (replaced_contents, replacement_count) = replace_versions_in_string(&contents, versions);
if replacement_count > 0 {
fs::write(path, replaced_contents.as_bytes())
.wrap_err_with(|| format!("failed to write back to {:?}", path))?;
}
Ok(replacement_count)
}

pub fn replace_versions_in_string<'a>(
s: &'a str,
versions: &HashMap<String, String>,
) -> (Cow<'a, str>, usize) {
let mut replacement_count = 0;
let replaced_s = VERSIONS_REGEX.replace_all(s, |caps: &Captures| {
if let Some(version) = versions.get(&caps[1]) {
replacement_count += 1;
version.clone()
} else {
// leave unchanged
caps[0].to_string()
}
Br1ght0ne marked this conversation as resolved.
Show resolved Hide resolved
});
(replaced_s, replacement_count)
}

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

fn test_versions() -> HashMap<String, String> {
[("fuels", "0.47.0"), ("fuel-types", "0.35.3")]
.map(|(name, version)| (name.to_string(), version.to_string()))
.into()
}

#[test]
fn test_valid_replacements() {
let s = "docs.rs/fuels/{{versions.fuels}}/fuels\ndocs.rs/fuel-types/{{versions.fuel-types}}/fuel-types";
let versions = test_versions();
let (replaced, count) = replace_versions_in_string(s, &versions);
assert_eq!(
replaced,
format!(
"docs.rs/fuels/{}/fuels\ndocs.rs/fuel-types/{}/fuel-types",
versions["fuels"], versions["fuel-types"]
)
);
assert_eq!(count, 2);
}

#[test]
fn test_invalid_replacement() {
let s = "```rust,ignore
{{#include ../../../examples/contracts/src/lib.rs:deployed_contracts}}
```";
let versions = test_versions();
let (replaced, count) = replace_versions_in_string(s, &versions);
assert_eq!(replaced, s);
assert_eq!(count, 0);
}

#[test]
fn test_invalid_package_name() {
let s = "docs.rs/fuels-wrong-name/{{versions.fuels-wrong-name}}/fuels-wrong-name";
let versions = test_versions();
let (replaced, count) = replace_versions_in_string(s, &versions);
assert_eq!(replaced, s);
assert_eq!(count, 0);
}
}
Loading