diff options
| -rw-r--r-- | .gitignore | 1 | ||||
| -rw-r--r-- | Cargo.lock | 34 | ||||
| -rw-r--r-- | Cargo.toml | 14 | ||||
| -rw-r--r-- | LICENSE-APACHE | 202 | ||||
| -rw-r--r-- | LICENSE-MIT | 9 | ||||
| -rw-r--r-- | README.md | 22 | ||||
| -rw-r--r-- | src/fmt_case_style.rs | 382 | ||||
| -rw-r--r-- | src/fmt_path.rs | 232 | ||||
| -rw-r--r-- | src/lib.rs | 48 |
9 files changed, 944 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..2c1cc55 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,34 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "just_fmt" +version = "0.1.0" +dependencies = [ + "strip-ansi-escapes", +] + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "strip-ansi-escapes" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a8f8038e7e7969abb3f1b7c2a811225e9296da208539e0f79c5251d6cac0025" +dependencies = [ + "vte", +] + +[[package]] +name = "vte" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "231fdcd7ef3037e8330d8e17e61011a2c244126acc0a982f4040ac3f9f0bc077" +dependencies = [ + "memchr", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..5fea8e4 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "just_fmt" +authors = ["Weicao-CatilGrass"] +description = "Just a crate for formatting some things" + +readme = "README.md" +license = "MIT OR Apache-2.0" +repository = "https://github.com/catilgrass/just_fmt" + +version = "0.1.0" +edition = "2024" + +[dependencies] +strip-ansi-escapes = "0.2.1" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..51eefef --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Weicao-CatilGrass + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..4ff38a3 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,9 @@ +# The MIT License (MIT) + +Copyright © 2026 Weicao-CatilGrass + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..787015b --- /dev/null +++ b/README.md @@ -0,0 +1,22 @@ +# just_fmt + +> Just a crate for formatting some things + +## Modules + +- `just_fmt::fmt_case_style`: Provides conversion for common naming case styles. +- `just_fmt::fmt_path`: Provides string formatting capabilities. + +## Installation + +Add the dependency to your `Cargo.toml`: + +```toml +[dependencies] +just_fmt = "0.1.0" +``` + +## License + +This project is dual-licensed under MIT and Apache 2.0. +See the LICENSE file for details. diff --git a/src/fmt_case_style.rs b/src/fmt_case_style.rs new file mode 100644 index 0000000..076bdd3 --- /dev/null +++ b/src/fmt_case_style.rs @@ -0,0 +1,382 @@ +pub struct CaseFormatter { + content: Vec<String>, +} + +impl From<String> for CaseFormatter { + fn from(value: String) -> Self { + Self { + content: str_split(value), + } + } +} + +impl From<&String> for CaseFormatter { + fn from(value: &String) -> Self { + Self { + content: str_split(value.clone()), + } + } +} + +impl From<&str> for CaseFormatter { + fn from(value: &str) -> Self { + Self { + content: str_split(value.to_string()), + } + } +} + +/// Split the string into segments for conversion +fn str_split(input: String) -> Vec<String> { + let mut result = String::new(); + let mut prev_space = false; + + for c in input.chars() { + match c { + 'a'..='z' | 'A'..='Z' | '0'..='9' => { + result.push(c); + prev_space = false; + } + '_' | ',' | '.' | '-' | ' ' => { + if !prev_space { + result.push(' '); + prev_space = true; + } + } + _ => {} + } + } + + let mut processed = String::new(); + let mut chars = result.chars().peekable(); + + while let Some(c) = chars.next() { + processed.push(c); + + // Detect case boundaries: + // when the current character is lowercase and the next is uppercase (e.g., "bre[wC]offee") + // Treat as a word boundary in PascalCase or camelCase, insert a space + if let Some(&next) = chars.peek() + && c.is_lowercase() + && next.is_uppercase() + { + processed.push(' '); + } + } + + processed + .to_lowercase() + .split_whitespace() + .map(|s| s.to_string()) + .collect() +} + +impl CaseFormatter { + /// Convert to camelCase format (brewCoffee) + /// + /// # Examples + /// + /// ``` + /// # use just_fmt::fmt_case_style::CaseFormatter; + /// let processor = CaseFormatter::from("brew_coffee"); + /// assert_eq!(processor.to_camel_case(), "brewCoffee"); + /// ``` + pub fn to_camel_case(&self) -> String { + let mut result = String::new(); + for (i, word) in self.content.iter().enumerate() { + if i == 0 { + result.push_str(&word.to_lowercase()); + } else { + let mut chars = word.chars(); + if let Some(first) = chars.next() { + result.push_str(&first.to_uppercase().collect::<String>()); + result.push_str(&chars.collect::<String>().to_lowercase()); + } + } + } + result + } + + /// Convert to PascalCase format (BrewCoffee) + /// + /// # Examples + /// + /// ``` + /// # use just_fmt::fmt_case_style::CaseFormatter; + /// let processor = CaseFormatter::from("brew_coffee"); + /// assert_eq!(processor.to_pascal_case(), "BrewCoffee"); + /// ``` + pub fn to_pascal_case(&self) -> String { + let mut result = String::new(); + for word in &self.content { + let mut chars = word.chars(); + if let Some(first) = chars.next() { + result.push_str(&first.to_uppercase().collect::<String>()); + result.push_str(&chars.collect::<String>().to_lowercase()); + } + } + result + } + + /// Convert to kebab-case format (brew-coffee) + /// + /// # Examples + /// + /// ``` + /// # use just_fmt::fmt_case_style::CaseFormatter; + /// let processor = CaseFormatter::from("brew_coffee"); + /// assert_eq!(processor.to_kebab_case(), "brew-coffee"); + /// ``` + pub fn to_kebab_case(&self) -> String { + self.content.join("-").to_lowercase() + } + + /// Convert to snake_case format (brew_coffee) + /// + /// # Examples + /// + /// ``` + /// # use just_fmt::fmt_case_style::CaseFormatter; + /// let processor = CaseFormatter::from("brewCoffee"); + /// assert_eq!(processor.to_snake_case(), "brew_coffee"); + /// ``` + pub fn to_snake_case(&self) -> String { + self.content.join("_").to_lowercase() + } + + /// Convert to dot.case format (brew.coffee) + /// + /// # Examples + /// + /// ``` + /// # use just_fmt::fmt_case_style::CaseFormatter; + /// let processor = CaseFormatter::from("brew_coffee"); + /// assert_eq!(processor.to_dot_case(), "brew.coffee"); + /// ``` + pub fn to_dot_case(&self) -> String { + self.content.join(".").to_lowercase() + } + + /// Convert to Title Case format (Brew Coffee) + /// + /// # Examples + /// + /// ``` + /// # use just_fmt::fmt_case_style::CaseFormatter; + /// let processor = CaseFormatter::from("brew_coffee"); + /// assert_eq!(processor.to_title_case(), "Brew Coffee"); + /// ``` + pub fn to_title_case(&self) -> String { + let mut result = String::new(); + for word in &self.content { + let mut chars = word.chars(); + if let Some(first) = chars.next() { + result.push_str(&first.to_uppercase().collect::<String>()); + result.push_str(&chars.collect::<String>().to_lowercase()); + } + result.push(' '); + } + result.pop(); + result + } + + /// Convert to lower case format (brew coffee) + /// + /// # Examples + /// + /// ``` + /// # use just_fmt::fmt_case_style::CaseFormatter; + /// let processor = CaseFormatter::from("BREW COFFEE"); + /// assert_eq!(processor.to_lower_case(), "brew coffee"); + /// ``` + pub fn to_lower_case(&self) -> String { + self.content.join(" ").to_lowercase() + } + + /// Convert to UPPER CASE format (BREW COFFEE) + /// + /// # Examples + /// + /// ``` + /// # use just_fmt::fmt_case_style::CaseFormatter; + /// let processor = CaseFormatter::from("brew coffee"); + /// assert_eq!(processor.to_upper_case(), "BREW COFFEE"); + /// ``` + pub fn to_upper_case(&self) -> String { + self.content.join(" ").to_uppercase() + } +} + +#[cfg(test)] +mod tests { + use crate::fmt_case_style::CaseFormatter; + + #[test] + fn test_processer() { + let test_cases = vec![ + ("brew_coffee", "brewCoffee"), + ("brew, coffee", "brewCoffee"), + ("brew-coffee", "brewCoffee"), + ("Brew.Coffee", "brewCoffee"), + ("bRewCofFee", "bRewCofFee"), + ("brewCoffee", "brewCoffee"), + ("b&rewCoffee", "brewCoffee"), + ("BrewCoffee", "brewCoffee"), + ("brew.coffee", "brewCoffee"), + ("Brew_Coffee", "brewCoffee"), + ("BREW COFFEE", "brewCoffee"), + ]; + + for (input, expected) in test_cases { + let processor = CaseFormatter::from(input); + assert_eq!( + processor.to_camel_case(), + expected, + "Failed for input: '{}'", + input + ); + } + } + + #[test] + fn test_conversions() { + let processor = CaseFormatter::from("brewCoffee"); + + assert_eq!(processor.to_upper_case(), "BREW COFFEE"); + assert_eq!(processor.to_lower_case(), "brew coffee"); + assert_eq!(processor.to_title_case(), "Brew Coffee"); + assert_eq!(processor.to_dot_case(), "brew.coffee"); + assert_eq!(processor.to_snake_case(), "brew_coffee"); + assert_eq!(processor.to_kebab_case(), "brew-coffee"); + assert_eq!(processor.to_pascal_case(), "BrewCoffee"); + assert_eq!(processor.to_camel_case(), "brewCoffee"); + } +} + +/// Convert to camelCase format (brewCoffee) +/// +/// # Examples +/// +/// ``` +/// # use just_fmt::camel_case; +/// assert_eq!(camel_case!("brew_coffee"), "brewCoffee"); +/// ``` +#[macro_export] +macro_rules! camel_case { + ($input:expr) => {{ + use just_fmt::fmt_case_style::CaseFormatter; + CaseFormatter::from($input).to_camel_case() + }}; +} + +/// Convert to UPPER CASE format (BREW COFFEE) +/// +/// # Examples +/// +/// ``` +/// # use just_fmt::upper_case; +/// assert_eq!(upper_case!("brew coffee"), "BREW COFFEE"); +/// ``` +#[macro_export] +macro_rules! upper_case { + ($input:expr) => {{ + use just_fmt::fmt_case_style::CaseFormatter; + CaseFormatter::from($input).to_upper_case() + }}; +} + +/// Convert to lower case format (brew coffee) +/// +/// # Examples +/// +/// ``` +/// # use just_fmt::lower_case; +/// assert_eq!(lower_case!("BREW COFFEE"), "brew coffee"); +/// ``` +#[macro_export] +macro_rules! lower_case { + ($input:expr) => {{ + use just_fmt::fmt_case_style::CaseFormatter; + CaseFormatter::from($input).to_lower_case() + }}; +} + +/// Convert to Title Case format (Brew Coffee) +/// +/// # Examples +/// +/// ``` +/// # use just_fmt::title_case; +/// assert_eq!(title_case!("brew_coffee"), "Brew Coffee"); +/// ``` +#[macro_export] +macro_rules! title_case { + ($input:expr) => {{ + use just_fmt::fmt_case_style::CaseFormatter; + CaseFormatter::from($input).to_title_case() + }}; +} + +/// Convert to dot.case format (brew.coffee) +/// +/// # Examples +/// +/// ``` +/// # use just_fmt::dot_case; +/// assert_eq!(dot_case!("brew_coffee"), "brew.coffee"); +/// ``` +#[macro_export] +macro_rules! dot_case { + ($input:expr) => {{ + use just_fmt::fmt_case_style::CaseFormatter; + CaseFormatter::from($input).to_dot_case() + }}; +} + +/// Convert to snake_case format (brew_coffee) +/// +/// # Examples +/// +/// ``` +/// # use just_fmt::snake_case; +/// assert_eq!(snake_case!("brewCoffee"), "brew_coffee"); +/// ``` +#[macro_export] +macro_rules! snake_case { + ($input:expr) => {{ + use just_fmt::fmt_case_style::CaseFormatter; + CaseFormatter::from($input).to_snake_case() + }}; +} + +/// Convert to kebab-case format (brew-coffee) +/// +/// # Examples +/// +/// ``` +/// # use just_fmt::kebab_case; +/// assert_eq!(kebab_case!("brew_coffee"), "brew-coffee"); +/// ``` +#[macro_export] +macro_rules! kebab_case { + ($input:expr) => {{ + use just_fmt::fmt_case_style::CaseFormatter; + CaseFormatter::from($input).to_kebab_case() + }}; +} + +/// Convert to PascalCase format (BrewCoffee) +/// +/// # Examples +/// +/// ``` +/// # use just_fmt::pascal_case; +/// assert_eq!(pascal_case!("brew_coffee"), "BrewCoffee"); +/// ``` +#[macro_export] +macro_rules! pascal_case { + ($input:expr) => {{ + use just_fmt::fmt_case_style::CaseFormatter; + CaseFormatter::from($input).to_pascal_case() + }}; +} diff --git a/src/fmt_path.rs b/src/fmt_path.rs new file mode 100644 index 0000000..4b15fe4 --- /dev/null +++ b/src/fmt_path.rs @@ -0,0 +1,232 @@ +use std::path::{Path, PathBuf}; + +#[derive(PartialEq, Eq, Clone, Copy, Debug)] +pub struct PathFormatConfig { + /// Whether to strip ANSI escape sequences (e.g., `\x1b[31m`, `\x1b[0m`). + /// When the path string may contain terminal color codes, enabling this option will clean them up. + pub strip_ansi: bool, + + /// Whether to strip characters disallowed in Windows filenames (`*`, `?`, `"`, `<`, `>`, `|`). + /// These characters typically have special meaning or are not allowed in filesystems. + pub strip_unfriendly_chars: bool, + + /// Whether to resolve parent directory references (`..`). + /// When enabled, attempts to navigate upward in the path, e.g., `/a/b/../c` becomes `/a/c`. + /// Note: This operation is based solely on the path string itself, without accessing the actual filesystem. + pub resolve_parent_dirs: bool, + + /// Whether to collapse consecutive forward slashes (`/`). + /// For example, `/home//user` becomes `/home/user`. + pub collapse_consecutive_slashes: bool, + + /// Whether to escape backslashes (`\`) to forward slashes (`/`). + /// This helps unify Windows‑style paths to Unix style, facilitating cross‑platform handling. + pub escape_backslashes: bool, +} + +impl Default for PathFormatConfig { + fn default() -> Self { + Self { + strip_ansi: true, + strip_unfriendly_chars: true, + resolve_parent_dirs: true, + collapse_consecutive_slashes: true, + escape_backslashes: true, + } + } +} + +/// Normalize an input path string into a canonical, platform‑agnostic form. +/// +/// This function removes ANSI escape sequences, unifies separators to `/`, +/// collapses duplicate slashes, strips unfriendly characters (`*`, `?`, `"`, `<`, `>`, `|`), +/// resolves simple `..` components, and preserves a trailing slash when present. +/// +/// See examples below for the exact normalization behavior. +/// +/// # Examples +/// +/// ``` +/// # use just_fmt::fmt_path::fmt_path_str; +/// # use just_fmt::fmt_path::FormatPathError; +/// +/// # fn main() -> Result<(), FormatPathError> { +/// assert_eq!(fmt_path_str("C:\\Users\\\\test")?, "C:/Users/test"); +/// assert_eq!( +/// fmt_path_str("/path/with/*unfriendly?chars")?, +/// "/path/with/unfriendlychars" +/// ); +/// assert_eq!(fmt_path_str("\x1b[31m/path\x1b[0m")?, "/path"); +/// assert_eq!(fmt_path_str("/home/user/dir/")?, "/home/user/dir/"); +/// assert_eq!( +/// fmt_path_str("/home/user/file.txt")?, +/// "/home/user/file.txt" +/// ); +/// assert_eq!( +/// fmt_path_str("/home/my_user/DOCS/JVCS_TEST/Workspace/../Vault/")?, +/// "/home/my_user/DOCS/JVCS_TEST/Vault/" +/// ); +/// assert_eq!(fmt_path_str("./home/file.txt")?, "home/file.txt"); +/// assert_eq!(fmt_path_str("./home/path/")?, "home/path/"); +/// assert_eq!(fmt_path_str("./")?, ""); +/// # Ok(()) +/// # } +/// ``` +pub fn fmt_path_str(path: impl Into<String>) -> Result<String, FormatPathError> { + fmt_path_str_custom(path, &PathFormatConfig::default()) +} + +/// Normalize an input path string into a canonical, platform‑agnostic form. +/// +/// This function removes ANSI escape sequences, unifies separators to `/`, +/// collapses duplicate slashes, strips unfriendly characters (`*`, `?`, `"`, `<`, `>`, `|`), +/// resolves simple `..` components, and preserves a trailing slash when present. +/// +/// Unlike `fmt_path_str`, +/// this method uses `PathFormatConfig` to precisely control +/// what should be processed +pub fn fmt_path_str_custom( + path: impl Into<String>, + config: &PathFormatConfig, +) -> Result<String, FormatPathError> { + let path_str = path.into(); + let ends_with_slash = path_str.ends_with('/'); + + // ANSI Strip + let cleaned = if config.strip_ansi { + strip_ansi_escapes::strip(&path_str) + } else { + path_str.as_bytes().to_vec() + }; + let path_without_ansi = String::from_utf8(cleaned).map_err(FormatPathError::InvalidUtf8)?; + + let path_with_forward_slash = if config.escape_backslashes { + path_without_ansi.replace('\\', "/") + } else { + path_without_ansi + }; + let mut result = String::new(); + let mut prev_char = '\0'; + + for c in path_with_forward_slash.chars() { + if config.collapse_consecutive_slashes && c == '/' && prev_char == '/' { + continue; + } + result.push(c); + prev_char = c; + } + + if config.strip_unfriendly_chars { + let unfriendly_chars = ['*', '?', '"', '<', '>', '|']; + result = result + .chars() + .filter(|c| !unfriendly_chars.contains(c)) + .collect(); + } + + // Handle ".." path components + let path_buf = PathBuf::from(&result); + let normalized_path = if config.resolve_parent_dirs { + normalize_path(&path_buf) + } else { + path_buf + }; + result = normalized_path.to_string_lossy().replace('\\', "/"); + + // Restore trailing slash if original path had one + if ends_with_slash && !result.ends_with('/') { + result.push('/'); + } + + // Special case: when result is only "./", return "" + if result == "./" { + return Ok(String::new()); + } + + Ok(result) +} + +/// Normalize path by resolving ".." components without requiring file system access +fn normalize_path(path: &Path) -> PathBuf { + let mut components = Vec::new(); + + for component in path.components() { + match component { + std::path::Component::ParentDir => { + if !components.is_empty() { + components.pop(); + } + } + std::path::Component::CurDir => { + // Skip current directory components + } + _ => { + components.push(component); + } + } + } + + if components.is_empty() { + PathBuf::from(".") + } else { + components.iter().collect() + } +} + +/// Format a [`PathBuf`] into its canonical string form and convert it back. +/// +/// This is a convenience wrapper around [`fmt_path_str`], preserving +/// the semantics of [`PathBuf`] while applying the same normalization rules: +/// - normalize separators to `/` +/// - remove duplicated separators +/// - strip ANSI escape sequences +/// - remove unfriendly characters (`*`, `?`, etc.) +/// - resolve simple `..` segments +pub fn fmt_path(path: impl Into<PathBuf>) -> Result<PathBuf, FormatPathError> { + let path_str = fmt_path_str(path.into().display().to_string())?; + Ok(PathBuf::from(path_str)) +} + +/// Format a [`PathBuf`] into its canonical string form and convert it back. +/// +/// Unlike `fmt_path`, +/// this method uses `PathFormatConfig` to precisely control +/// what should be processed +pub fn fmt_path_custom( + path: impl Into<PathBuf>, + config: &PathFormatConfig, +) -> Result<PathBuf, FormatPathError> { + let path_str = fmt_path_str_custom(path.into().display().to_string(), config)?; + Ok(PathBuf::from(path_str)) +} + +/// Error type for path formatting operations. +#[derive(Debug)] +pub enum FormatPathError { + /// The input string contained invalid UTF-8 after stripping ANSI escape sequences. + InvalidUtf8(std::string::FromUtf8Error), +} + +impl std::fmt::Display for FormatPathError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + FormatPathError::InvalidUtf8(e) => { + write!(f, "Invalid UTF-8 after ANSI stripping: {}", e) + } + } + } +} + +impl std::error::Error for FormatPathError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + FormatPathError::InvalidUtf8(e) => Some(e), + } + } +} + +impl From<std::string::FromUtf8Error> for FormatPathError { + fn from(e: std::string::FromUtf8Error) -> Self { + FormatPathError::InvalidUtf8(e) + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..6c486d7 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,48 @@ +/// Format naming styles +/// +/// Provides multiple naming style conversion functions, supporting conversion from input strings +/// in different formats to standardized word lists, then outputting to various common naming styles. +/// +/// # Main Features +/// +/// - Create `CaseFormatter` from a string +/// - Intelligently split input strings into word lists, handling multiple separators and case boundaries +/// - Convert to multiple naming formats: `camelCase`, `PascalCase`, `snake_case`, `kebab-case`, etc. +/// +/// # Examples +/// +/// ``` +/// # use just_fmt::fmt_case::CaseFormatter; +/// // Using CaseFormatter +/// let formatter = CaseFormatter::from("brew_coffee"); +/// assert_eq!(formatter.to_camel_case(), "brewCoffee"); +/// assert_eq!(formatter.to_pascal_case(), "BrewCoffee"); +/// assert_eq!(formatter.to_snake_case(), "brew_coffee"); +/// assert_eq!(formatter.to_kebab_case(), "brew-coffee"); +/// +/// // Using macros +/// # use just_fmt::fmt_case::{camel_case, pascal_case, snake_case, kebab_case} +/// assert_eq!(camel_case!("brew coffee"), "brewCoffee"); +/// assert_eq!(pascal_case!("brewCoffee"), "BrewCoffee"); +/// assert_eq!(snake_case!("brew_coffee"), "brew_coffee"); +/// assert_eq!(kebab_case!("brew.Coffee"), "brew-coffee"); +/// ``` +/// +/// # Supported Input Separators +/// +/// The module can recognize the following characters as word separators: +/// - Underscore `_` +/// - Comma `,` +/// - Dot `.` +/// - Hyphen `-` +/// - Space ` ` +/// +/// It can also automatically detect case boundaries (e.g., "camel" and "Case" in "camelCase") +pub mod fmt_case_style; + +/// Normalize an input path string into a canonical, platform‑agnostic form. +/// +/// This function removes ANSI escape sequences, unifies separators to `/`, +/// collapses duplicate slashes, strips unfriendly characters (`*`, `?`, `"`, `<`, `>`, `|`), +/// resolves simple `..` components, and preserves a trailing slash when present. +pub mod fmt_path; |
