commit 6df315115b13471d1e4eae24b8c4d5af6019bfcf Author: dschlueter Date: Tue Mar 18 03:05:18 2025 +0100 Initial commit diff --git a/.NameToUnix.conf b/.NameToUnix.conf new file mode 100644 index 0000000..eef94b1 --- /dev/null +++ b/.NameToUnix.conf @@ -0,0 +1,28 @@ +# .NameToUnix.conf (TOML) +# -------------------------------------------- +# In dieser Datei können beliebige zusätzliche Schlüssel-Werte-Paare unter [replacements] hinterlegt werden, +# die im Dateistammnamen ersetzt werden. Zum Beispiel: +# +# [replacements] +# "foo" = "bar" +# "old" = "neu" +# +# Dadurch werden in den Dateinamen alle "foo" durch "bar" ersetzt, und "old" durch "neu". +# WICHTIG: Die hartcodierten Transformationen sind aber immer vorrangig und lassen sich auch nicht rückgängig machen. +# Weitere Einstellungen können analog ergänzt werden, wenn man das Struct "Config" erweitert. + +[replacements] +".." = "." +"_·_" = "_-_" +".-_" = "_-_" +"Ä" = "Ae" +"Ö" = "Oe" +"Ü" = "Ue" +"ä" = "ae" +"ö" = "oe" +"ü" = "ue" +"ß" = "ss" +"O'Reilly" = "OReilly" +"O_Reilly" = "OReilly" +# "" = "" + diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml new file mode 100644 index 0000000..e8ffb75 --- /dev/null +++ b/.github/workflows/build.yaml @@ -0,0 +1,62 @@ +name: Build and Test + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +env: + CARGO_TERM_COLOR: always + +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + rust: [stable] + + steps: + - uses: actions/checkout@v4 + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: ${{ matrix.rust }} + override: true + components: rustfmt, clippy + + - name: Cache dependencies + uses: actions/cache@v3 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + target + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + restore-keys: ${{ runner.os }}-cargo- + + - name: Format check + uses: actions-rs/cargo@v1 + with: + command: fmt + args: --all -- --check + + - name: Clippy check + uses: actions-rs/cargo@v1 + with: + command: clippy + args: -- -D warnings + + - name: Build + uses: actions-rs/cargo@v1 + with: + command: build + args: --verbose + + - name: Run tests + uses: actions-rs/cargo@v1 + with: + command: test + args: --verbose diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7b20914 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +/target/* +**/*.rs.bk +Cargo.lock +.idea/ +.vscode/ +*.swp +*.swo +.DS_Store +/testverzeichnis/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..88227c3 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,136 @@ +# Contributing to CONTRIBUTING.md + +First off, thanks for taking the time to contribute! ❤️ + +All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉 + +> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about: +> - Star the project +> - Tweet about it +> - Refer this project in your project's readme +> - Mention the project at local meetups and tell your friends/colleagues + + +## Table of Contents + +- [Code of Conduct](#code-of-conduct) +- [I Have a Question](#i-have-a-question) +- [I Want To Contribute](#i-want-to-contribute) +- [Reporting Bugs](#reporting-bugs) +- [Suggesting Enhancements](#suggesting-enhancements) +- [Your First Code Contribution](#your-first-code-contribution) +- [Improving The Documentation](#improving-the-documentation) +- [Styleguides](#styleguides) +- [Commit Messages](#commit-messages) +- [Join The Project Team](#join-the-project-team) + + +## Code of Conduct + +This project and everyone participating in it is governed by the +[CONTRIBUTING.md Code of Conduct](blob/master/CODE_OF_CONDUCT.md). +By participating, you are expected to uphold this code. Please report unacceptable behavior +to . + + +## I Have a Question + +> If you want to ask a question, we assume that you have read the available [Documentation](). + +Before you ask a question, it is best to search for existing [Issues](/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first. + +If you then still feel the need to ask a question and need clarification, we recommend the following: + +- Open an [Issue](/issues/new). +- Provide as much context as you can about what you're running into. +- Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. + +We will then take care of the issue as soon as possible. + + + +## I Want To Contribute + +> ### Legal Notice +> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license. + +### Reporting Bugs + + +#### Before Submitting a Bug Report + +A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible. + +- Make sure that you are using the latest version. +- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](). If you are looking for support, you might want to check [this section](#i-have-a-question)). +- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](issues?q=label%3Abug). +- Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue. +- Collect information about the bug: +- Stack trace (Traceback) +- OS, Platform and Version (Windows, Linux, macOS, x86, ARM) +- Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant. +- Possibly your input and the output +- Can you reliably reproduce the issue? And can you also reproduce it with older versions? + + +#### How Do I Submit a Good Bug Report? + + +We use GitHub issues to track bugs and errors. If you run into an issue with the project: + +- Open an [Issue](/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.) +- Explain the behavior you would expect and the actual behavior. +- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case. +- Provide the information you collected in the previous section. + +Once it's filed: + +- The project team will label the issue accordingly. +- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced. +- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#your-first-code-contribution). + + + + +### Suggesting Enhancements + +This section guides you through submitting an enhancement suggestion for CONTRIBUTING.md, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions. + + +#### Before Submitting an Enhancement + +- Make sure that you are using the latest version. +- Read the [documentation]() carefully and find out if the functionality is already covered, maybe by an individual configuration. +- Perform a [search](/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. +- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library. + + +#### How Do I Submit a Good Enhancement Suggestion? + +Enhancement suggestions are tracked as [GitHub issues](/issues). + +- Use a **clear and descriptive title** for the issue to identify the suggestion. +- Provide a **step-by-step description of the suggested enhancement** in as many details as possible. +- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you. +- You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. +- **Explain why this enhancement would be useful** to most CONTRIBUTING.md users. You may also want to point out the other projects that solved it better and which could serve as inspiration. + + + +### Your First Code Contribution + + +### Improving The Documentation + + +## Styleguides +### Commit Messages + + +## Join The Project Team + + + +## Attribution +This guide is based on the **contributing.md**. [Make your own](https://contributing.md/)! + diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..2e77799 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,63 @@ +[package] +name = "NameToUnix" +version = "0.1.0" +edition = "2021" +authors = ["Dieter Schlüter "] +description = "Ein Tool zum Anpassen von Verzeichnis- und Dateinamen an Linux-Konventionen" +license = "MIT" +readme = "README.md" +repository = "https://github.com/jamulix/NameToUnix" +keywords = ["filesystem", "rename", "sanitize", "cli"] +categories = ["command-line-utilities", "filesystem"] + +[dependencies] +# Bereits verwendete Abhängigkeiten +clap = { version = "4.5.27", features = ["derive"] } +serde = { version = "1.0", features = ["derive"] } +toml = "0.8.11" +walkdir = "2.4.0" +glob = "0.3.1" +unicode-segmentation = "1.10.0" +emojis = "0.6.1" +regex = "1.10.3" +dirs = "5.0.1" + +# Neue empfohlene Abhängigkeiten +anyhow = "1.0.80" # Verbesserte Fehlerbehandlung +thiserror = "1.0.57" # Typisierte Fehler +once_cell = "1.19.0" # Lazy-Initialisierung für statische Werte +rayon = "1.9.0" # Parallelverarbeitung +indicatif = "0.17.7" # Fortschrittsbalken +env_logger = "0.11.2" # Logging-Framework +log = "0.4.21" # Logging-Abstraktionen +itertools = "0.12.1" # Erweiterte Iterator-Funktionalität + +[dev-dependencies] +tempfile = "3.10.1" # Temporäre Dateien für Tests +assert_fs = "1.1.1" # Dateisystem-Assertions für Tests +predicates = "3.1.0" # Prädikate für Tests + +[profile.release] +lto = true # Link-Time-Optimierung +codegen-units = 1 # Optimierung für Binärgröße +opt-level = 3 # Maximale Optimierung +panic = "abort" # Kleinere Binärdatei durch Abbrechen bei Panic +strip = true # Entfernen von Debug-Symbolen + +[package.metadata.deb] +maintainer = "Dieter Schlüter " +copyright = "2025, Dieter Schlüter" +license-file = ["LICENSE", "4"] +extended-description = """ +NameToUnix ist ein Kommandozeilen-Tool zum Umbenennen von Dateien und Verzeichnissen, +um sie mit Linux-Dateinamen-Konventionen kompatibel zu machen. Es ersetzt Leerzeichen und +Sonderzeichen durch Unterstriche und konvertiert deutsche Umlaute in ihre ASCII-Pendants. +""" +depends = "$auto" +section = "utils" +priority = "optional" +assets = [ + ["target/release/NameToUnix", "usr/bin/", "755"], + ["README.md", "usr/share/doc/NameToUnix/README", "644"], +] + diff --git a/Infotext.txt b/Infotext.txt new file mode 100644 index 0000000..3f8b79b --- /dev/null +++ b/Infotext.txt @@ -0,0 +1,765 @@ +## Übersicht: Projekt_Struktur.txt + +```text +NameToUnix/ +├── Cargo.toml # Projektmetadaten und Abhängigkeiten +├── Cargo.lock # Exakte Versionen der Abhängigkeiten (automatisch generiert) +├── .gitignore # Dateien, die von Git ignoriert werden sollen +├── README.md # Projektdokumentation +├── CONTRIBUTING.md # Mitarbeiten-Dokumentation +├── LICENSE # Lizenzinformationen +├── .NameToUnix.conf # Konfigurationsdatei (Übersetzungsregeln: 'foo' = 'bar') +├── .github/ # CI/CD und GitHub-spezifische Dateien +│ └── workflows/ # Kompilier-Anweisungen +│ └── build.yaml # GitHub Actions Workflow für Build und Release +├── src/ # Quellcode-Verzeichnis +│ ├── main.rs # Haupteinstiegspunkt (bereits vorhanden) +│ ├── cli.rs # CLI-Argumente und Parsing +│ ├── config.rs # Konfigurationsverwaltung +│ └── sanitizer.rs # Kernlogik zur Dateinamenbereinigung +├── Infotest.txt # Infotext-Datei, Dokumentation, die vieles erklärt +└── test/ # Test-Programm + └── create_test_tree.sh # Shell-Skript erzeugt 21 Test-Verzeichnisse mit 400 Dateien mit skurrilen Namen + +``` + +Lass mich die wichtigsten zusätzlichen Dateien genauer beschreiben: + +## 1. README.md + + +# NameToUnix + +Ein leistungsstarkes Kommandozeilen-Tool zum Bereinigen von Dateinamen gemäß Linux-Konventionen. Es ist sinnvoll, +wenn viele Dateinamen z. B. nach einem Download und Entpacken von Zip-Dateien aus Windows-Dateisystemen +Leerzeichen enthalten. Es erspart enorm viel Zeit durch automatisches Umbenennen, d.h. Ersetzen der störenden Zeichen. + +## Funktionen + +- Ersetzt Leerzeichen und Sonderzeichen durch Unterstriche +- Konvertiert deutsche Umlaute in ihre ASCII-Pendants (ä → ae, usw.) +- Unterstützt rekursive Verarbeitung von Verzeichnissen +- Bietet Vorschau-Modus ohne tatsächliche Änderungen +- Ermöglicht benutzerdefinierte Ersetzungsregeln über Konfigurationsdatei +- Unterstützt Ausschlussmuster für bestimmte Dateien/Verzeichnisse + +## Installation + +### Über Cargo + +```bash +cargo install NameToUnix +``` + +### Manueller Build + +```bash +git clone https://github.com/username/NameToUnix.git +cd NameToUnix +cargo build --release +``` + +Die ausführbare Datei wird dann unter `target/release/NameToUnix` erstellt. + +## Verwendung + +```bash +# Grundlegende Verwendung +NameToUnix /pfad/zu/dateien + +# Nur Vorschau der Änderungen ohne tatsächliche Umbenennung +NameToUnix -n /pfad/zu/dateien + +# Mehrere Pfade verarbeiten +NameToUnix /pfad1 /pfad2 /pfad3 + +# Bestimmte Dateien ausschließen +NameToUnix -e "*.tmp" -e "backup_*" /pfad/zu/dateien + +# Verbosity erhöhen +NameToUnix -v /pfad/zu/dateien + +# Auch das Wurzelverzeichnis umbenennen +NameToUnix --modify-root /pfad/zu/dateien +``` + +## Konfiguration + +Erstelle eine Datei `.NameToUnix.conf` im Arbeitsverzeichnis mit folgendem Inhalt: + +```toml +[replacements] +"foo" = "bar" +"alt" = "neu" +".." = "." +"_·_" = "_-_" +"Ä" = "Ae" +"Ö" = "Oe" +"Ü" = "Ue" +"ä" = "ae" +"ö" = "oe" +"ü" = "ue" +"ß" = "ss" +``` + +## Lizenz + +Dieses Projekt steht unter der MIT-Lizenz - siehe die [LICENSE](LICENSE)-Datei für Details. + +## Mitwirken + +Beiträge sind willkommen! Bitte lies [CONTRIBUTING.md](CONTRIBUTING.md) für Details zum Prozess für Pull Requests. + + +## 2. .gitignore + +```text +/target +**/*.rs.bk +Cargo.lock +.idea/ +.vscode/ +*.swp +*.swo +.DS_Store +.NameToUnix.conf +/test-files/ + +``` + +## 3. LICENSE + +```text +MIT License + +Copyright (c) 2025 Dieter Schlüter + +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. + +``` + +## 4. src/cli.rs + +```rust +use clap::{ArgGroup, Parser}; +use std::path::PathBuf; + +/// Command-line interface für das Umbenennungsprogramm +#[derive(Parser, Debug, Clone)] +#[clap(about, version, author)] +#[clap(group( + ArgGroup::new("mode") + .args(&["no_changes", "force"]) + .multiple(false) +))] +pub struct Cli { + /// Pfade (Dateien und Verzeichnisse) zum rekursiven Anpassen + pub paths: Vec, + + /// Ausgaben unterdrücken (keine Umbenennungsinfos auf stdout) + #[clap(short, long)] + pub quiet: bool, + + /// Nur anzeigen, aber keine realen Änderungen vornehmen + #[clap(short, long)] + pub no_changes: bool, + + /// Existierende Dateien überschreiben + #[clap(short, long)] + pub force: bool, + + /// Zu ignorierende Muster (-e "*.py", mehrere können angegeben werden) + #[clap(short = 'e', long, value_name = "PATTERN")] + pub exclude: Vec, + + /// Ausführliche Debug-Informationen + #[clap(short = 'v', long)] + pub verbose: bool, + + /// Erlaubt, auch das Wurzelverzeichnis anzupassen + #[clap(long)] + pub modify_root: bool, +} +``` + +## 5. src/config.rs + +```rust +use anyhow::{Context, Result}; +use log::{debug, info}; +use serde::Deserialize; +use std::collections::HashMap; +use std::fs; +use std::path::Path; + +/// Repräsentiert die Konfiguration, die sich aus einer TOML-Datei laden lässt. +#[derive(Deserialize, Default, Debug, Clone)] +#[serde(default)] +pub struct Config { + /// Individuelle Ersetzungen, z. B. "foo" => "bar" + pub replacements: HashMap, +} + +impl Config { + /// Liest eine TOML-Konfigurationsdatei ein, wenn sie existiert. + fn load_internal(path: &Path, verbose: bool) -> Result { + if path.exists() { + if verbose { + debug!("Lade Konfigurationsdatei: {}", path.display()); + } + let content = fs::read_to_string(path).with_context(|| { + format!("Konnte Konfigurationsdatei nicht lesen: {}", path.display()) + })?; + let loaded: Self = toml::from_str(&content).with_context(|| { + format!( + "Konnte Konfigurationsdatei nicht parsen: {}", + path.display() + ) + })?; + if verbose && !loaded.replacements.is_empty() { + debug!("Eingelesene Replacements:"); + for (k, v) in &loaded.replacements { + debug!(" {:?} => {:?}", k, v); + } + } + Ok(loaded) + } else { + Err(anyhow::anyhow!("Datei existiert nicht: {}", path.display())) + } + } + + /// Öffentliche Methode zum Laden einer Konfiguration aus einem Pfad + pub fn load(path: &str, verbose: bool) -> Result { + let cfg_path = Path::new(path); + match Self::load_internal(cfg_path, verbose) { + Ok(config) => Ok(config), + Err(_) => { + if verbose { + info!( + "Keine Konfigurationsdatei '{}' gefunden. Verwende Standardwerte.", + path + ); + } + Ok(Self::default()) + } + } + } + /// Sucht nach Konfigurationsdateien in verschiedenen Orten und kombiniert sie + pub fn from_default_locations(verbose: bool) -> Result { + // Prioritätenreihenfolge (später überschreibt früher): + // 1. Standard etc-Verzeichnis (/etc/NameToUnix/config.toml) + // 2. Benutzerverzeichnis (~/.config/NameToUnix/config.toml) + // 3. Arbeitsverzeichnis (./.NameToUnix.conf) + // Die Ladereihenfolge ist so gewählt, dass lokale Einstellungen Vorrang vor + // Benutzereinstellungen haben und diese wiederum Vorrang vor Systemeinstellungen. + + // Wir beginnen mit einer leeren Konfiguration + let mut config = Self::default(); + let mut config_found = false; + + // Standard etc-Verzeichnis + let etc_config = Path::new("/etc/NameToUnix/config.toml"); + if etc_config.exists() { + if verbose { + debug!("Lade System-Konfiguration: {}", etc_config.display()); + } + if let Ok(etc_conf) = Self::load(etc_config.to_str().unwrap_or_default(), verbose) { + // Füge die Werte zur Konfiguration hinzu + config.replacements.extend(etc_conf.replacements); + config_found = true; + } + } else if verbose { + debug!( + "System-Konfiguration nicht gefunden: {}", + etc_config.display() + ); + } + + // Benutzerverzeichnis + if let Some(home) = dirs::home_dir() { + let user_config = home.join(".config/NameToUnix/config.toml"); + if user_config.exists() { + if verbose { + debug!("Lade Benutzer-Konfiguration: {}", user_config.display()); + } + if let Ok(user_conf) = Self::load(user_config.to_str().unwrap_or_default(), verbose) + { + // Überschreibe/ergänze mit Benutzerkonfiguration + config.replacements.extend(user_conf.replacements); + config_found = true; + } + } else if verbose { + debug!( + "Benutzer-Konfiguration nicht gefunden: {}", + user_config.display() + ); + } + } + + // Arbeitsverzeichnis (höchste Priorität) + let local_config = Path::new(".NameToUnix.conf"); + if local_config.exists() { + if verbose { + debug!("Lade lokale Konfiguration: {}", local_config.display()); + } + if let Ok(local_conf) = Self::load(local_config.to_str().unwrap_or_default(), verbose) { + // Überschreibe/ergänze mit lokaler Konfiguration + config.replacements.extend(local_conf.replacements); + config_found = true; + } + } else if verbose { + debug!( + "Lokale Konfiguration nicht gefunden: {}", + local_config.display() + ); + } + + // Gib die kombinierte Konfiguration zurück + if config_found { + if verbose && !config.replacements.is_empty() { + info!( + "Kombinierte Konfiguration enthält {} Ersetzungen", + config.replacements.len() + ); + } + } else { + if verbose { + info!("Keine Konfigurationsdateien gefunden. Verwende nur die Standardwerte."); + } + } + + Ok(config) + } +} +``` + +## 6. src/sanitizer.rs + +```rust +use crate::config::Config; +use emojis; +use glob::Pattern; +use log::{debug, warn}; +use once_cell::sync::Lazy; +use regex::{Captures, Regex}; +use std::ffi::OsStr; +use std::path::Path; +use unicode_segmentation::UnicodeSegmentation; +use walkdir::DirEntry; + +// Regex-Patterns als statische Variablen für bessere Performance +static RE_INVALID: Lazy = Lazy::new(|| Regex::new(r"[^\w.\-]").unwrap()); +static RE_ADJACENT: Lazy = Lazy::new(|| Regex::new(r"_\.|\._").unwrap()); +static RE_MULTI: Lazy = Lazy::new(|| Regex::new(r"[_\.]{2,}").unwrap()); + +/// Bereinigt den übergebenen Dateinamen oder Verzeichnisnamen. +pub fn clean_filename(name: &OsStr, config: &Config, verbose: bool) -> Option { + let original = name.to_string_lossy(); + + // Stamm und Extension trennen + let (mut base, mut ext) = match original.rsplit_once('.') { + Some((b, e)) => (b.to_string(), format!(".{e}")), + None => (original.to_string(), String::new()), + }; + + // Platzhalter (C++, c++, C#, c#) anlegen + base = preserve_special_identifiers(&base); + ext = preserve_special_identifiers(&ext); + + // 1) Konfig-Replacements zuerst + for (k, v) in &config.replacements { + base = base.replace(k, v); + } + + // 2) Dann erst hart-codierte Ersetzungen anwenden + base = apply_hardcoded_replacements(&base); + + // 3) Emojis und hochgestellte Zeichen ersetzen + base = replace_emojis_and_superscript(&base); + + // 4) Entfernen/Ersetzen aller übrigen ungültigen Zeichen + base = RE_INVALID.replace_all(&base, "_").to_string(); + + // Ungültige Kombinationen aus Punkt und Unterstrich + base = RE_ADJACENT.replace_all(&base, ".").to_string(); + + // Mehrfache Punkte/Unterstriche auf einen reduzieren + base = RE_MULTI + .replace_all( + &base, + |caps: &Captures| { + if caps[0].contains('.') { + "." + } else { + "_" + } + }, + ) + .to_string(); + + // Führender Punkt soll bleiben, führende Unterstriche sollen verschwinden + base = trim_leading_underscores_preserve_leading_dot(&base); + + // Überflüssige Unterstriche und Punkte am Ende beseitigen + base = base.trim_end_matches('_').to_string(); + base = base.trim_end_matches('.').to_string(); + + // Falls komplett geleert, "unnamed" + if base.is_empty() { + base = "unnamed".to_string(); + } + + // Endgültigen Dateinamen zusammenbauen + let mut result = format!("{}{}", base, ext); + + // Platzhalter zurückverwandeln + result = restore_special_identifiers(&result); + + // Falls --verbose und sich der Name geändert hat + if verbose && result != original { + debug!("Transformiert: '{}' -> '{}'", original, result); + } + + // Keine Änderung -> None zurückgeben + if result == *original { + None + } else { + Some(result) + } +} + +/// Schützt spezielle Identifikatoren vor der Umwandlung +fn preserve_special_identifiers(input: &str) -> String { + input + .replace("C++", "CPLUSPLUS") + .replace("c++", "cplusplus") + .replace("C#", "CSHARP") + .replace("c#", "csharp") +} + +/// Stellt spezielle Identifikatoren wieder her +fn restore_special_identifiers(input: &str) -> String { + input + .replace("CPLUSPLUS", "C++") + .replace("cplusplus", "c++") + .replace("CSHARP", "C#") + .replace("csharp", "c#") +} + +/// Fasst alle fest eingebauten Ersetzungen zusammen. +fn apply_hardcoded_replacements(input: &str) -> String { + input + .replace('\'', "") // Apostroph entfernen + .replace("ˆ", "_") +} + +/// Entfernt am Anfang nur Unterstriche, einen führenden Punkt (.) bewahrt es. +fn trim_leading_underscores_preserve_leading_dot(s: &str) -> String { + let mut chars = s.chars().peekable(); + let mut result = String::new(); + + if let Some('.') = chars.peek() { + // Nimm den Punkt + result.push('.'); + chars.next(); + + // Entferne anschließend führende Unterstriche hinter dem Punkt + while let Some('_') = chars.peek() { + chars.next(); + } + } else { + // Entferne führende Unterstriche + while let Some('_') = chars.peek() { + chars.next(); + } + } + + // Restliche Zeichen anfügen + result.extend(chars); + result +} + +/// Ersetzt Emojis und hochgestellte Zeichen (z. B. ²³⁴) durch '_'. +fn replace_emojis_and_superscript(input: &str) -> String { + input + .graphemes(true) + .map(|g| { + if emojis::get(g).is_some() { + "_".to_string() + } else if is_superscript(g) { + "_".to_string() + } else { + g.to_string() + } + }) + .collect() +} + +/// Prüft, ob alle Zeichen ein Superscript sind (z. B. ²³⁴). +fn is_superscript(g: &str) -> bool { + g.chars().all(|c| { + c == '\u{00AA}' + || c == '\u{00BA}' + || (c >= '\u{00B2}' && c <= '\u{00B3}') + || c == '\u{00B9}' + || (c >= '\u{2070}' && c <= '\u{209F}') + }) +} + +/// Prüft, ob der Pfad aufgrund der Ausschlussmuster ignoriert werden soll. +pub fn is_excluded(entry: &DirEntry, patterns: &[Pattern]) -> bool { + let path = entry.path(); + patterns.iter().any(|p| p.matches_path(path)) +} + +/// Überprüft, ob eine Umbenennungsoperation sicher ist +pub fn is_safe_rename(src: &Path, dst: &Path, force: bool) -> bool { + if src.exists() && dst.exists() && !force { + warn!( + "Ziel existiert bereits und --force nicht gesetzt: {}", + dst.display() + ); + return false; + } + + // Prüfen auf zusätzliche Sicherheitsrisiken + // z.B. Systemdateien, schreibgeschützte Verzeichnisse, etc. + + true +} +``` + +## 7. src/main.rs + +```rust +// Verwende nun die Module +mod cli; +mod config; +mod sanitizer; + +use anyhow::{Context, Result}; +use clap::Parser; +use cli::Cli; +use config::Config; +use glob::Pattern; +use indicatif::{ProgressBar, ProgressStyle}; +use log::{debug, error, info}; +use sanitizer::{clean_filename, is_excluded, is_safe_rename}; +use std::fs; +use walkdir::WalkDir; + +/// Startpunkt des Programms +fn main() -> Result<()> { + // Initialisiere Logger + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); + + // Argumente parsen + let args = Cli::parse(); + + // Optional Konfigurationsdatei laden + let config = Config::from_default_locations(args.verbose)?; + // let config = Config::load(".NameToUnix.conf", args.verbose)?; + + // Ausschlussmuster (Glob-Patterns) vorbereiten + let exclude_patterns = args + .exclude + .iter() + .map(|pattern| { + Pattern::new(pattern) + .with_context(|| format!("Ungültiges Ausschlussmuster: {}", pattern)) + }) + .collect::>>()?; + + if args.verbose && !exclude_patterns.is_empty() { + debug!("Folgende Exclude-Pattern werden genutzt:"); + for p in &exclude_patterns { + debug!(" {}", p.as_str()); + } + } + + // Für alle angegebenen Pfade + for path in &args.paths { + // Alle Einträge sammeln, damit zuerst die tiefsten umbenannt werden + let mut entries = Vec::new(); + for entry_result in WalkDir::new(path) + .into_iter() + .filter_entry(|e| !is_excluded(e, &exclude_patterns)) + { + if let Ok(entry) = entry_result { + entries.push(entry); + } else if let Err(e) = entry_result { + error!("Fehler beim Durchlaufen von {}: {}", path.display(), e); + } + } + + // Aufsteigend nach Tiefe sortieren, dann umkehren => tiefste Einträge zuerst + entries.sort_by_key(|e| e.depth()); + entries.reverse(); + + // Fortschrittsbalken bei größeren Dateimengen + let progress_bar = if !args.quiet && entries.len() > 50 { + let bar = ProgressBar::new(entries.len() as u64); + bar.set_style(ProgressStyle::default_bar() + .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} ({eta}) {msg}")? + .progress_chars("#>-")); + Some(bar) + } else { + None + }; + + // Umbenennen in absteigender Tiefe + for entry in entries { + if let Some(bar) = &progress_bar { + bar.inc(1); + } + + let old_path = entry.path(); + + // Ebenentiefe 0 -> überspringen wir als Verzeichnis, außer --modify_root ist gesetzt + if entry.depth() == 0 { + if entry.file_type().is_dir() && !args.modify_root { + if args.verbose { + debug!("Skip root directory: {}", old_path.display()); + } + continue; + } + } + + // Dateiname (oder Verzeichnisname) ermitteln + let filename = old_path.file_name().ok_or_else(|| { + anyhow::anyhow!( + "Konnte Dateinamen nicht ermitteln für: {}", + old_path.display() + ) + })?; + + // Verarbeiten und ggf. umbenennen + if let Some(new_name) = clean_filename(filename, &config, args.verbose) { + let new_path = old_path.with_file_name(&new_name); + + if !args.quiet { + info!("{} -> {}", old_path.display(), new_path.display()); + } + + if !args.no_changes { + if is_safe_rename(old_path, &new_path, args.force) { + fs::rename(old_path, &new_path).with_context(|| { + format!( + "Fehler beim Umbenennen: {} -> {}", + old_path.display(), + new_path.display() + ) + })?; + } + } + } + } + + if let Some(bar) = &progress_bar { + bar.finish_with_message("Umbenennung abgeschlossen"); + } + } + + Ok(()) +} +``` + + +## 8. ./github/workflows/build.yaml -- GitHub Actions Workflow für CI/CD + +```yaml +name: Build and Test + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +env: + CARGO_TERM_COLOR: always + +jobs: + build: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + rust: [stable] + + steps: + - uses: actions/checkout@v4 + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: ${{ matrix.rust }} + override: true + components: rustfmt, clippy + + - name: Cache dependencies + uses: actions/cache@v3 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + target + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + restore-keys: ${{ runner.os }}-cargo- + + - name: Format check + uses: actions-rs/cargo@v1 + with: + command: fmt + args: --all -- --check + + - name: Clippy check + uses: actions-rs/cargo@v1 + with: + command: clippy + args: -- -D warnings + + - name: Build + uses: actions-rs/cargo@v1 + with: + command: build + args: --verbose + + - name: Run tests + uses: actions-rs/cargo@v1 + with: + command: test + args: --verbose +``` + +## Zusammenfassung + +Diese Dateien bilden zusammen ein vollständiges, gut strukturiertes Rust-Projekt für den `NameToUnix`. +Die wichtigsten Aspekte sind: + +1. **Modularisierung**: Der Code ist in logische Module aufgeteilt (cli.rs, config.rs, sanitizer.rs) +2. **Verbesserte Fehlerbehandlung**: Verwendung von `anyhow` für bessere Fehlermeldungen +3. **Dokumentation**: Ausführliche README.md mit Anwendungsbeispielen +4. **Tests**: Test-Skript zur Überprüfung der Funktionalität +5. **CI/CD**: Aktionen für automatisierte Tests und Builds +6. **Konfiguration**: Erweiterte Konfigurationsmöglichkeiten +7. **Benutzerfreundlichkeit**: Fortschrittsbalken für große Dateimengen + +Diese Struktur folgt den Rust-Best-Practices und macht das Projekt wartbar, erweiterbar und benutzerfreundlich. + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..bc4cd61 --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2025 Dieter Schlüter + +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/Projekt_Struktur.txt b/Projekt_Struktur.txt new file mode 100644 index 0000000..93d8ba9 --- /dev/null +++ b/Projekt_Struktur.txt @@ -0,0 +1,17 @@ +NameToUnix/ +├── Cargo.toml # Projektmetadaten und Abhängigkeiten +├── Cargo.lock # Exakte Versionen der Abhängigkeiten (automatisch generiert) +├── .gitignore # Dateien, die von Git ignoriert werden sollen +├── .NameToUnix.conf # Konfigurationsdatei (Übersetzungsregeln: 'foo' = 'bar') +├── README.md # Projektdokumentation +├── CONTRIBUTING.md # Contribute-Dokumentation +├── .github/ # CI/CD und GitHub-spezifische Dateien +│ └── workflows/ +│ └── build.yml # GitHub Actions Workflow für Build and Release +├── src/ # Quellcode-Verzeichnis +│ ├── main.rs # Haupteinstiegspunkt (bereits vorhanden) +│ ├── cli.rs # CLI-Argumente und Parsing +│ ├── config.rs # Konfigurationsverwaltung +│ └── sanitizer.rs # Kernlogik zur Dateinamenbereinigung +└── LICENSE # Lizenzinformationen + diff --git a/README.md b/README.md new file mode 100644 index 0000000..b49b288 --- /dev/null +++ b/README.md @@ -0,0 +1,85 @@ +# Filename Sanitizer + +Ein leistungsstarkes Kommandozeilen-Tool zum Bereinigen von Dateinamen gemäß Linux-Konventionen. +Es funktioniert unter Linux (und MacOS, nicht getestet). + +(c) 2025 Dieter Schlüter + +## Funktionen + +- Ersetzt Leerzeichen und Sonderzeichen in Datei- und Verzeichnisnamen durch Unterstriche +- Konvertiert deutsche Umlaute in ihre ASCII-Pendants (ä → ae, usw.) +- Unterstützt rekursive Verarbeitung von Verzeichnissen +- Bietet Vorschau-Modus ohne tatsächliche Änderungen +- Ermöglicht benutzerdefinierte Ersetzungsregeln über Konfigurationsdatei +- Unterstützt Ausschlussmuster für bestimmte Datei-Muster/Verzeichnis-Muster + +## Installation + +### Über Cargo + +```bash +cargo install NameToUnix +``` + +### Manueller Build + +```bash +git clone https://github.com/jamulix/NameToUnix.git +cd NameToUnix +cargo build --release +``` + +Die ausführbare Datei wird dann unter `target/release/NameToUnix` erstellt. + +## Verwendung + +```bash +# Grundlegende Verwendung +NameToUnix /pfad/zu/dateien + +# Nur Vorschau der Änderungen ohne tatsächliche Umbenennung +NameToUnix -n /pfad/zu/dateien + +# Mehrere Pfade verarbeiten +NameToUnix /pfad1 /pfad2 /pfad3 + +# Bestimmte Dateien ausschließen +NameToUnix -e "*.tmp" -e "backup_*" /pfad/zu/dateien + +# Verbosity erhöhen +NameToUnix -v /pfad/zu/dateien + +# Auch das Wurzelverzeichnis umbenennen +NameToUnix --modify-root /pfad/zu/dateien +``` + +## Konfiguration + +Erstelle eine Datei `.NameToUnix.conf` im Arbeitsverzeichnis mit folgendem Inhalt: +(alternativ: ~/.config/NameToUnix/config.toml) + +```toml +[replacements] +"foo" = "bar" +"old" = "new" +"alt" = "neu" +".." = "." +"_·_" = "_-_" +"Ä" = "Ae" +"Ö" = "Oe" +"Ü" = "Ue" +"ä" = "ae" +"ö" = "oe" +"ü" = "ue" +"ß" = "ss" +``` + +## Lizenz + +Dieses Projekt steht unter der MIT-Lizenz - siehe die [LICENSE](LICENSE)-Datei für Details. + +## Mitwirken + +Beiträge sind willkommen! Bitte lies [CONTRIBUTING.md](CONTRIBUTING.md) für Details zum Prozess für Pull Requests. + diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..997cb9c --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,39 @@ +use clap::{ArgGroup, Parser}; +use std::path::PathBuf; + +/// Command-line interface für das Umbenennungsprogramm +#[derive(Parser, Debug, Clone)] +#[clap(about, version, author)] +#[clap(group( + ArgGroup::new("mode") + .args(&["no_changes", "force"]) + .multiple(false) +))] +pub struct Cli { + /// Pfade (Dateien und Verzeichnisse) zum rekursiven Anpassen + pub paths: Vec, + + /// Ausgaben unterdrücken (keine Umbenennungsinfos auf stdout) + #[clap(short, long)] + pub quiet: bool, + + /// Nur anzeigen, aber keine realen Änderungen vornehmen + #[clap(short, long)] + pub no_changes: bool, + + /// Existierende Dateien überschreiben + #[clap(short, long)] + pub force: bool, + + /// Zu ignorierende Muster (-e "*.py", mehrere können angegeben werden) + #[clap(short = 'e', long, value_name = "PATTERN")] + pub exclude: Vec, + + /// Ausführliche Debug-Informationen + #[clap(short = 'v', long)] + pub verbose: bool, + + /// Erlaubt, auch das Wurzelverzeichnis anzupassen + #[clap(long)] + pub modify_root: bool, +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..08c124e --- /dev/null +++ b/src/config.rs @@ -0,0 +1,146 @@ +use anyhow::{Context, Result}; +use log::{debug, info}; +use serde::Deserialize; +use std::collections::HashMap; +use std::fs; +use std::path::Path; + +/// Repräsentiert die Konfiguration, die sich aus einer TOML-Datei laden lässt. +#[derive(Deserialize, Default, Debug, Clone)] +#[serde(default)] +pub struct Config { + /// Individuelle Ersetzungen, z. B. "foo" => "bar" + pub replacements: HashMap, +} + +impl Config { + /// Liest eine TOML-Konfigurationsdatei ein, wenn sie existiert. + fn load_internal(path: &Path, verbose: bool) -> Result { + if path.exists() { + if verbose { + debug!("Lade Konfigurationsdatei: {}", path.display()); + } + let content = fs::read_to_string(path).with_context(|| { + format!("Konnte Konfigurationsdatei nicht lesen: {}", path.display()) + })?; + let loaded: Self = toml::from_str(&content).with_context(|| { + format!( + "Konnte Konfigurationsdatei nicht parsen: {}", + path.display() + ) + })?; + if verbose && !loaded.replacements.is_empty() { + debug!("Eingelesene Replacements:"); + for (k, v) in &loaded.replacements { + debug!(" {:?} => {:?}", k, v); + } + } + Ok(loaded) + } else { + Err(anyhow::anyhow!("Datei existiert nicht: {}", path.display())) + } + } + + /// Öffentliche Methode zum Laden einer Konfiguration aus einem Pfad + pub fn load(path: &str, verbose: bool) -> Result { + let cfg_path = Path::new(path); + match Self::load_internal(cfg_path, verbose) { + Ok(config) => Ok(config), + Err(_) => { + if verbose { + info!( + "Keine Konfigurationsdatei '{}' gefunden. Verwende Standardwerte.", + path + ); + } + Ok(Self::default()) + } + } + } + /// Sucht nach Konfigurationsdateien in verschiedenen Orten und kombiniert sie + pub fn from_default_locations(verbose: bool) -> Result { + // Prioritätenreihenfolge (später überschreibt früher): + // 1. Standard etc-Verzeichnis (/etc/NameToUnix/config.toml) + // 2. Benutzerverzeichnis (~/.config/NameToUnix/config.toml) + // 3. Arbeitsverzeichnis (./.NameToUnix.conf) + // Die Ladereihenfolge ist so gewählt, dass lokale Einstellungen Vorrang vor + // Benutzereinstellungen haben und diese wiederum Vorrang vor Systemeinstellungen. + + // Wir beginnen mit einer leeren Konfiguration + let mut config = Self::default(); + let mut config_found = false; + + // Standard etc-Verzeichnis + let etc_config = Path::new("/etc/NameToUnix/config.toml"); + if etc_config.exists() { + if verbose { + debug!("Lade System-Konfiguration: {}", etc_config.display()); + } + if let Ok(etc_conf) = Self::load(etc_config.to_str().unwrap_or_default(), verbose) { + // Füge die Werte zur Konfiguration hinzu + config.replacements.extend(etc_conf.replacements); + config_found = true; + } + } else if verbose { + debug!( + "System-Konfiguration nicht gefunden: {}", + etc_config.display() + ); + } + + // Benutzerverzeichnis + if let Some(home) = dirs::home_dir() { + let user_config = home.join(".config/NameToUnix/config.toml"); + if user_config.exists() { + if verbose { + debug!("Lade Benutzer-Konfiguration: {}", user_config.display()); + } + if let Ok(user_conf) = Self::load(user_config.to_str().unwrap_or_default(), verbose) + { + // Überschreibe/ergänze mit Benutzerkonfiguration + config.replacements.extend(user_conf.replacements); + config_found = true; + } + } else if verbose { + debug!( + "Benutzer-Konfiguration nicht gefunden: {}", + user_config.display() + ); + } + } + + // Arbeitsverzeichnis (höchste Priorität) + let local_config = Path::new(".NameToUnix.conf"); + if local_config.exists() { + if verbose { + debug!("Lade lokale Konfiguration: {}", local_config.display()); + } + if let Ok(local_conf) = Self::load(local_config.to_str().unwrap_or_default(), verbose) { + // Überschreibe/ergänze mit lokaler Konfiguration + config.replacements.extend(local_conf.replacements); + config_found = true; + } + } else if verbose { + debug!( + "Lokale Konfiguration nicht gefunden: {}", + local_config.display() + ); + } + + // Gib die kombinierte Konfiguration zurück + if config_found { + if verbose && !config.replacements.is_empty() { + info!( + "Kombinierte Konfiguration enthält {} Ersetzungen", + config.replacements.len() + ); + } + } else { + if verbose { + info!("Keine Konfigurationsdateien gefunden. Verwende nur die Standardwerte."); + } + } + + Ok(config) + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..91f5bcc --- /dev/null +++ b/src/main.rs @@ -0,0 +1,130 @@ +// Verwende nun die Module +mod cli; +mod config; +mod sanitizer; + +use anyhow::{Context, Result}; +use clap::Parser; +use cli::Cli; +use config::Config; +use glob::Pattern; +use indicatif::{ProgressBar, ProgressStyle}; +use log::{debug, error, info}; +use sanitizer::{clean_filename, is_excluded, is_safe_rename}; +use std::fs; +use walkdir::WalkDir; + +/// Startpunkt des Programms +fn main() -> Result<()> { + // Initialisiere Logger + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); + + // Argumente parsen + let args = Cli::parse(); + + // Optional Konfigurationsdatei laden + let config = Config::from_default_locations(args.verbose)?; + // let config = Config::load(".NameToUnix.conf", args.verbose)?; + + // Ausschlussmuster (Glob-Patterns) vorbereiten + let exclude_patterns = args + .exclude + .iter() + .map(|pattern| { + Pattern::new(pattern) + .with_context(|| format!("Ungültiges Ausschlussmuster: {}", pattern)) + }) + .collect::>>()?; + + if args.verbose && !exclude_patterns.is_empty() { + debug!("Folgende Exclude-Pattern werden genutzt:"); + for p in &exclude_patterns { + debug!(" {}", p.as_str()); + } + } + + // Für alle angegebenen Pfade + for path in &args.paths { + // Alle Einträge sammeln, damit zuerst die tiefsten umbenannt werden + let mut entries = Vec::new(); + for entry_result in WalkDir::new(path) + .into_iter() + .filter_entry(|e| !is_excluded(e, &exclude_patterns)) + { + if let Ok(entry) = entry_result { + entries.push(entry); + } else if let Err(e) = entry_result { + error!("Fehler beim Durchlaufen von {}: {}", path.display(), e); + } + } + + // Aufsteigend nach Tiefe sortieren, dann umkehren => tiefste Einträge zuerst + entries.sort_by_key(|e| e.depth()); + entries.reverse(); + + // Fortschrittsbalken bei größeren Dateimengen + let progress_bar = if !args.quiet && entries.len() > 50 { + let bar = ProgressBar::new(entries.len() as u64); + bar.set_style(ProgressStyle::default_bar() + .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} ({eta}) {msg}")? + .progress_chars("#>-")); + Some(bar) + } else { + None + }; + + // Umbenennen in absteigender Tiefe + for entry in entries { + if let Some(bar) = &progress_bar { + bar.inc(1); + } + + let old_path = entry.path(); + + // Ebenentiefe 0 -> überspringen wir als Verzeichnis, außer --modify_root ist gesetzt + if entry.depth() == 0 { + if entry.file_type().is_dir() && !args.modify_root { + if args.verbose { + debug!("Skip root directory: {}", old_path.display()); + } + continue; + } + } + + // Dateiname (oder Verzeichnisname) ermitteln + let filename = old_path.file_name().ok_or_else(|| { + anyhow::anyhow!( + "Konnte Dateinamen nicht ermitteln für: {}", + old_path.display() + ) + })?; + + // Verarbeiten und ggf. umbenennen + if let Some(new_name) = clean_filename(filename, &config, args.verbose) { + let new_path = old_path.with_file_name(&new_name); + + if !args.quiet { + info!("{} -> {}", old_path.display(), new_path.display()); + } + + if !args.no_changes { + if is_safe_rename(old_path, &new_path, args.force) { + fs::rename(old_path, &new_path).with_context(|| { + format!( + "Fehler beim Umbenennen: {} -> {}", + old_path.display(), + new_path.display() + ) + })?; + } + } + } + } + + if let Some(bar) = &progress_bar { + bar.finish_with_message("Umbenennung abgeschlossen"); + } + } + + Ok(()) +} diff --git a/src/sanitizer.rs b/src/sanitizer.rs new file mode 100644 index 0000000..ff65696 --- /dev/null +++ b/src/sanitizer.rs @@ -0,0 +1,191 @@ +use crate::config::Config; +use emojis; +use glob::Pattern; +use log::{debug, warn}; +use once_cell::sync::Lazy; +use regex::{Captures, Regex}; +use std::ffi::OsStr; +use std::path::Path; +use unicode_segmentation::UnicodeSegmentation; +use walkdir::DirEntry; + +// Regex-Patterns als statische Variablen für bessere Performance +static RE_INVALID: Lazy = Lazy::new(|| Regex::new(r"[^\w.\-]").unwrap()); +static RE_ADJACENT: Lazy = Lazy::new(|| Regex::new(r"_\.|\._").unwrap()); +static RE_MULTI: Lazy = Lazy::new(|| Regex::new(r"[_\.]{2,}").unwrap()); + +/// Bereinigt den übergebenen Dateinamen oder Verzeichnisnamen. +pub fn clean_filename(name: &OsStr, config: &Config, verbose: bool) -> Option { + let original = name.to_string_lossy(); + + // Stamm und Extension trennen + let (mut base, mut ext) = match original.rsplit_once('.') { + Some((b, e)) => (b.to_string(), format!(".{e}")), + None => (original.to_string(), String::new()), + }; + + // Platzhalter (C++, c++, C#, c#) anlegen + base = preserve_special_identifiers(&base); + ext = preserve_special_identifiers(&ext); + + // 1) Konfig-Replacements zuerst + for (k, v) in &config.replacements { + base = base.replace(k, v); + } + + // 2) Dann erst hart-codierte Ersetzungen anwenden + base = apply_hardcoded_replacements(&base); + + // 3) Emojis und hochgestellte Zeichen ersetzen + base = replace_emojis_and_superscript(&base); + + // 4) Entfernen/Ersetzen aller übrigen ungültigen Zeichen + base = RE_INVALID.replace_all(&base, "_").to_string(); + + // Ungültige Kombinationen aus Punkt und Unterstrich + base = RE_ADJACENT.replace_all(&base, ".").to_string(); + + // Mehrfache Punkte/Unterstriche auf einen reduzieren + base = RE_MULTI + .replace_all( + &base, + |caps: &Captures| { + if caps[0].contains('.') { + "." + } else { + "_" + } + }, + ) + .to_string(); + + // Führender Punkt soll bleiben, führende Unterstriche sollen verschwinden + base = trim_leading_underscores_preserve_leading_dot(&base); + + // Überflüssige Unterstriche und Punkte am Ende beseitigen + base = base.trim_end_matches('_').to_string(); + base = base.trim_end_matches('.').to_string(); + + // Falls komplett geleert, "unnamed" + if base.is_empty() { + base = "unnamed".to_string(); + } + + // Endgültigen Dateinamen zusammenbauen + let mut result = format!("{}{}", base, ext); + + // Platzhalter zurückverwandeln + result = restore_special_identifiers(&result); + + // Falls --verbose und sich der Name geändert hat + if verbose && result != original { + debug!("Transformiert: '{}' -> '{}'", original, result); + } + + // Keine Änderung -> None zurückgeben + if result == *original { + None + } else { + Some(result) + } +} + +/// Schützt spezielle Identifikatoren vor der Umwandlung +fn preserve_special_identifiers(input: &str) -> String { + input + .replace("C++", "CPLUSPLUS") + .replace("c++", "cplusplus") + .replace("C#", "CSHARP") + .replace("c#", "csharp") +} + +/// Stellt spezielle Identifikatoren wieder her +fn restore_special_identifiers(input: &str) -> String { + input + .replace("CPLUSPLUS", "C++") + .replace("cplusplus", "c++") + .replace("CSHARP", "C#") + .replace("csharp", "c#") +} + +/// Fasst alle fest eingebauten Ersetzungen zusammen. +fn apply_hardcoded_replacements(input: &str) -> String { + input + .replace('\'', "") // Apostroph entfernen + .replace("ˆ", "_") +} + +/// Entfernt am Anfang nur Unterstriche, einen führenden Punkt (.) bewahrt es. +fn trim_leading_underscores_preserve_leading_dot(s: &str) -> String { + let mut chars = s.chars().peekable(); + let mut result = String::new(); + + if let Some('.') = chars.peek() { + // Nimm den Punkt + result.push('.'); + chars.next(); + + // Entferne anschließend führende Unterstriche hinter dem Punkt + while let Some('_') = chars.peek() { + chars.next(); + } + } else { + // Entferne führende Unterstriche + while let Some('_') = chars.peek() { + chars.next(); + } + } + + // Restliche Zeichen anfügen + result.extend(chars); + result +} + +/// Ersetzt Emojis und hochgestellte Zeichen (z. B. ²³⁴) durch '_'. +fn replace_emojis_and_superscript(input: &str) -> String { + input + .graphemes(true) + .map(|g| { + if emojis::get(g).is_some() { + "_".to_string() + } else if is_superscript(g) { + "_".to_string() + } else { + g.to_string() + } + }) + .collect() +} + +/// Prüft, ob alle Zeichen ein Superscript sind (z. B. ²³⁴). +fn is_superscript(g: &str) -> bool { + g.chars().all(|c| { + c == '\u{00AA}' + || c == '\u{00BA}' + || (c >= '\u{00B2}' && c <= '\u{00B3}') + || c == '\u{00B9}' + || (c >= '\u{2070}' && c <= '\u{209F}') + }) +} + +/// Prüft, ob der Pfad aufgrund der Ausschlussmuster ignoriert werden soll. +pub fn is_excluded(entry: &DirEntry, patterns: &[Pattern]) -> bool { + let path = entry.path(); + patterns.iter().any(|p| p.matches_path(path)) +} + +/// Überprüft, ob eine Umbenennungsoperation sicher ist +pub fn is_safe_rename(src: &Path, dst: &Path, force: bool) -> bool { + if src.exists() && dst.exists() && !force { + warn!( + "Ziel existiert bereits und --force nicht gesetzt: {}", + dst.display() + ); + return false; + } + + // Prüfen auf zusätzliche Sicherheitsrisiken + // z.B. Systemdateien, schreibgeschützte Verzeichnisse, etc. + + true +} diff --git a/test/create_test_tree.sh b/test/create_test_tree.sh new file mode 100755 index 0000000..06a093f --- /dev/null +++ b/test/create_test_tree.sh @@ -0,0 +1,81 @@ +#!/bin/bash +# create_test_tree.sh + +# Erzeugt ein Verzeichnis mit dem Namen $TOPDIR und 20 Unterverzeichnissen +# deren Namen aus zufälligen gewöhnichen und ungewöhnlichen Zeichen (s. chars) bestehen. +# Diese enthalten Dateien mit Basisnamen aus zufälligen gewöhnichen und ungewöhnlichen Zeichen +# und konventionellen Endungen (s. extensions). Der Inhalt ist ebenfalls zufällig. +# +# Dieser Dateibaum dient dann zum Testen des Rust-Programms NameToUnix : +# z. B. +# NameToUnix -n $TOPDIR (Option -n ==> Änderungen nur anzeigen) +# oder +# NameToUnix $TOPDIR +# +# +# (c) 2025 Dieter Schlüter + +TOPDIR="./testverzeichnis" + +# 1. Altes Testverzeichnis löschen +rm -rf "$TOPDIR" + +# 2. Neues Verzeichnis erstellen +mkdir -p "$TOPDIR" +cd "$TOPDIR" || exit + + +# Liste gewöhnicher und ungewöhnlicher Zeichen und Emojis + +chars=( + "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" + "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" + "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" + "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" + "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" + " " "  " "!" "@" "#" "$" "%" "^" "&" "*" "(" ")" + "=" "+" "[" "]" "{" "}" "|" "\\" ";" ":" "'" "\"" + "," "<" ">" "?" "~" "\`" "¡" "™" "£" "¢" "∞" "§" "¶" + "•" "ª" "º" "≠" "œ" "∑" "´" "®" "†" "¨" "ˆ" "ø" "π" + "“" "‘" "«" "…" "å" "ß" "∂" "ƒ" "©" "˙" "∆" "˚" "¬" + "Ω" "≈" "ç" "√" "∫" "˜" "µ" "≤" "≥" "÷" + "🦄" "👾" "💩" "🚀" "🎉" "😱" "🤯" "🌌" "💥" "🔧" "📁" +) + +# Liste üblicher Dateiendungen +extensions=("txt" "jpg" "png" "pdf" "docx" "xlsx" "pptx" + "zip" "tar.gz" "sh" "py" "js" "html" "css" + "php" "json" "xml" "csv" "log" "conf") + +# Zufälliger Datei/Verzeichnis Name Generator +generate_weird_name() { + local length=$(( RANDOM % 15 + 5 )) + for ((i=0; i "$dir_name/$file_name" 2>/dev/null + done +done + +# Beispielausgabe +echo "Testumgebung erstellt:" +tree -L 2 | head -n 20 +exit 0 +