init.py
Overview
This init.py file provides utility functions to handle filename uniqueness in the system, primarily by detecting and managing filename counters appended in parentheses (e.g., "file(1).txt"). It is part of the InfiniFlow project and facilitates generating unique filenames by checking existing names and appending incremental counters where necessary.
The key functionalities include:
Parsing filenames to extract base names and optional numeric counters.
Generating unique filenames by incrementing counters to avoid naming conflicts.
Importing the
UserServiceclass for external module usage.
This file typically serves as a utility module within a larger file management or user content system, ensuring that filename collisions are gracefully resolved.
Imported Entities
re: Python standard library module for regular expression operations.PurePathfrompathlib: Provides cross-platform path manipulations without accessing the filesystem.UserService: Imported from a sibling module.user_service, re-exported for external use.
Functions
split_name_counter(filename: str) -> tuple[str, int | None]
Purpose
Parses a filename string to separate the main part from an optional numeric counter enclosed in parentheses at the end of the base filename (before extension).
Parameters
filename(str): The filename string to parse. Expected format examples:"document" → no counter
"document(1)" → counter = 1
"document(12)" → counter = 12
Returns
tuple[str, int | None]: A tuple where:The first element is the main part of the filename (string).
The second element is the numeric counter (int) if present, else
None.
Behavior
Uses a regular expression to detect a numeric counter in parentheses at the end of the filename.
Strips trailing whitespace from the main part if a counter is found.
If no counter is found, returns the original filename and
None.
Example
split_name_counter("file(3)") # Returns: ("file", 3)
split_name_counter("report") # Returns: ("report", None)
split_name_counter("image (12)") # Returns: ("image ", 12)
duplicate_name(query_func, **kwargs) -> str
Purpose
Generates a unique filename by appending or incrementing a numeric counter in parentheses to avoid duplicates. It repeatedly queries an external function to check if the candidate filename already exists.
Parameters
query_func(callable): A function that accepts keyword arguments and returns:Trueif the filename exists (indicating a duplicate).Falseif the filename is available.
**kwargs: Arbitrary keyword arguments passed toquery_func. Must include:'name'(str): The original filename to check and modify.
Returns
str: A unique filename string that does not exist according toquery_func.If the original name is available, returns it unchanged.
Otherwise, returns a modified name with an appended or incremented counter, e.g.,
"file(1).txt","file(2).txt", etc.
Raises
KeyError: If the'name'key is missing inkwargs.RuntimeError: If a unique filename cannot be found within 1000 attempts.
Algorithm / Implementation Details
Starts with the original filename.
Calls
query_functo check for existence.If the name exists, uses
split_name_counterto parse the stem (filename without extension).Increments the counter found or starts at 1.
Constructs a new filename with the updated counter.
Repeats until an available name is found or max retries are reached.
Example Usage
existing_files = {"document.pdf", "document(1).pdf"}
def name_exists(name):
return name in existing_files
unique_name = duplicate_name(name_exists, name="document.pdf")
print(unique_name) # Outputs: "document(2).pdf"
Imported Classes
UserService
Imported and re-exported for convenience. No additional modifications are made here.
Interaction with Other Parts of the System
The file likely belongs to a module that manages user content or file storage.
duplicate_namedepends on aquery_funcsupplied by the caller, enabling flexible integration with databases, file systems, or other storage backends.UserServiceimport suggests this module is part of a larger user management or service layer.The filename uniqueness logic helps prevent conflicts in naming resources, which is critical in multi-user or collaborative environments.
Implementation Details and Notes
Uses
PurePathfrompathlibto cleanly separate filename stems and suffixes, ensuring correct handling of file extensions.The regular expression
r"^(.*?)((\d+))$"precisely matches filenames ending with a number in parentheses, e.g.,"filename(123)".The counter increment logic gracefully handles filenames with or without existing counters.
The maximum retry limit of 1000 prevents infinite loops in pathological cases.
The module includes comprehensive docstrings with type hints and usage examples, promoting maintainability and ease of use.
Mermaid Class Diagram
Since this file contains utility functions (not classes with properties), a flowchart illustrating the relationship between the functions is most appropriate.
flowchart TD
A[split_name_counter(filename)] -->|Returns main_part, counter| B[duplicate_name(query_func, **kwargs)]
B -->|Calls query_func with current name| C{Name Exists?}
C -- Yes --> B
C -- No --> D[Return unique filename]
Diagram Explanation:
duplicate_namedepends onsplit_name_counterto parse and increment counters.duplicate_namerelies on the externalquery_functo check name existence.The flow loops until an available name is found or the max retry limit is reached.
Summary
This init.py file provides robust utilities for managing filename uniqueness by parsing and incrementing counters within filenames. It is designed to integrate flexibly with external systems checking name availability and prevents conflicts through systematic renaming. The presence of UserService import indicates a broader user-related functionality within the module. This file is essential for any component requiring conflict-resistant filename management in the InfiniFlow project.