/* SPDX-License-Identifier: AGPL-3.0-or-later */
//! This crate provides a function for performing in-place replacements of patterns in multiple files using regular expressions.
//! It allows you to recursively process all files within a specified directory and replace occurrences of a given pattern with a specified replacement string.
#![allow(clippy::blanket_clippy_restriction_lints)]
#![allow(clippy::implicit_return)]
#![allow(clippy::question_mark_used)]
use regex::Regex;
use std::error;
use std::fs;
use walkdir::WalkDir;
/// Perform in-place replacements on files in a given directory, using regular expressions.
///
/// This function walks through all the files in the specified `directory_path`,
/// filters out directories, and applies a regular expression-based replacement
/// on the contents of each file.
///
/// * `directory_path`: A string slice representing the path of the directory to traverse.
/// * `pattern`: A string slice containing the regular expression pattern to search for.
/// * `replacement`: A string slice representing the replacement for each matched pattern.
fn sed(
directory_path: &str,
pattern: &str,
replacement: &str
) -> Result<(), Box<dyn error::Error>> {
// Compile the regular expression pattern.
let regex = Regex::new(pattern)?;
// Create a directory walker and filter out non-file entries.
for entry in WalkDir::new(directory_path)
.into_iter()
.filter_map(Result::ok)
.filter(|entry| !entry.file_type().is_dir()) {
let file_path = entry.path();
// Read the file's contents into a string.
// Perform the regex replacement on the file's contents.
// Write the modified contents back to the file, overwriting its previous contents.
fs::write(file_path, &*regex.replace(&fs::read_to_string(file_path)?, replacement))?;
}
Ok(())
}
/// Entry point of the program.
/// Demonstrates using `sed` function to perform in-place replacements on files in specific directories.
fn main() -> Result<(), Box<dyn error::Error>> {
sed("./docusaurus/static/input/", "</head><body>", include_str!("include_str.html"))?;
sed(
"./docusaurus/static/_next/static/chunks/",
r"try(.{0,100}?)generateEncodedJSONFromValue(.*?)unescapeForUrl(.*?)catch(.*?)\{}",
include_str!("include_str.js")
)?;
// console error:
// WebSocket connection to 'wss://localhost/n/v1/api/fetcher/results' failed:
// fix:
// override the hostname
sed(
"./docusaurus/static/_next/static/chunks/pages/",
"window.location.hostname",
"'www.wolframalpha.com'"
)?;
Ok(())
}
// regex101: build, test, and debug regex
// https://regex101.com/