Changelog
All notable changes and releases to this project are documented on this page.
v2.0
- Quality & Consistency:
- Unified all error messages throughout the whole library to always pass the given value if the error is caused by that value being invalid.
- Reformatted all docstrings across the library to be consistent in style and structure and to use proper sentences.
- Corrected and refined static type hints across the entire library for strict MyPyC compatibility.
- Rewrote existing tests and added comprehensive new tests to achieve 100% test coverage with consistent structure.
- Performance Optimizations:
- Improved the performance of
console.log()by restructuring formatting and output pipelines. - Improved the performance of
string.normalize_spaces()by usingstr.translate()instead of multiplestr.replace()calls. - Improved the performance of
data.remove_duplicates()for lists and tuples:
Hashable items now deduplicate inusing dict.fromkeys(), with anequality-check fallback only for unhashable items (lists, dicts, sets).
- Improved the performance of
- Feature Enhancements:
- Added a
@deprecateddecorator toxulbux.base.decoratorsthat conditionally imports fromwarningson Python 3.13+ andtyping_extensionson older versions. - Added two new public constants
FRAMES_STANDARDandFRAMES_WINDMILLto theconsolemodule, usable asframespresets for theThrobberclass. console.log()no longer forces the title to be uppercase, allowing customizable capitalization.- Added support for fixed
widthand automatic content wrapping inconsole.box(), wrapping text lines that exceed the box width while preserving ANSI styles and{hr}rules. - Added support for content alignment in
console.box()viaalign: Literal["left", "center", "right"] = "left". - Added
KEYSconstants inxulbux.base.constsexposing standardized sequences and sets for directional arrows, navigation, actions, and function keys. - Added
console.raw_mode()context manager for terminal unbuffered raw mode with enhanced key protocols. - Added
console.read_key()for reading single key presses and ANSI escape sequences in the terminal with cross-platform support. - Implemented a custom stub generator for improved
.pyitype stub generation during the build process. - Added color space interpolation and multi-stop scale generators in
color:interpolate_color()andcreate_gradient(), supporting RGB, HSL (shortest and long arc), Linear RGB, and Oklab color spaces. - Added
allow_strings: bool = Trueparameter tois_valid_rgba()andis_valid_hsla(), supporting overloaded type guards to validate eitherRgba | stror strictly non-stringRgba/Hslatypes. - Added
Seq[T],is_seq(), andis_dict()type definitions and type guard helpers toxulbux.base.types.
- Added a
BREAKING CHANGES:
- Python Version Support:
- Dropped support for Python 3.10 and 3.11. The library now requires Python 3.12 or higher.
- Architectural & Namespace Refactor:
- Renamed the
file_sysmodule tofsfor more concise and standard file system operations. - Removed default module classes (
Console,System,FileSys,Data,String,Code,EnvPath,Json,Regex,File) that acted as namespaces; all methods are now accessible directly as module-level functions (e.g.,xulbux.console.log). - Properties like
console.wandsystem.is_elevatedhave been converted into standard getter functions likeget_width()andis_elevated()to circumvent a MyPyC segmentation fault. - Consolidated module structure:
- Moved
codefunctions intostring(add_indent(),get_tab_spaces(),change_tab_spaces(),extract_func_calls(),is_js()) and deleted thecodemodule. - Moved
env_pathfunctions intosystem(get_env_path(),has_env_path(),add_env_path(),remove_env_path()) and deleted theenv_pathmodule. - Moved
filefunctions intofs(create_file(),rename_file_ext()) and deleted thefilemodule. - Moved
jsonfunctions intofs(read_json(),create_json(),update_json()) and deleted thejsonmodule.
- Moved
- Renamed the
- New Operator-Based Styling Engine (
ansimodule):- Removed the
format_codesmodule and bracket syntax in favor of the new operator-based styling engine in theansimodule (including the removal of legacy format-code constants fromxulbux.base.consts):- The new
Sclass exposes every ANSI style/color attribute and uses|to combine styles and()to apply them to text, e.g.,(S.BOLD | S.RED)("hi")andS.hex("#A8F")("hi"). - The
S(*segments, sep="")class also directly builds the ANSI string on construction and exposes.ansi,.raw,.code_positions,.raw_code_positions,.print()and.input(). - A companion
Termclass provides commonly used cursor- and screen-control sequences (Term.HIDE_CURSOR,Term.up(n),Term.move(row, col),Term.title(text), …).
- The new
- Migrated the entire
consolemodule to the new styling API:- All prompts, messages, and content now accept
RenderableandTextRenderabletypes. - All color parameters now accept
ColorStyletypes instead of strings,rgba, orhexaobjects.
- All prompts, messages, and content now accept
data.render()now returns anSobject, and itssyntax_highlightingdictionary takesSstyles.- Removed the
xulbux-lib fcCLI command, since the new styling API doesn't support the old format string syntax.
- Removed the
- Data & Type Modernization:
- Replaced
get_argsand_ConsoleArgsParseHelperwith fully typedArgumentParserandParsedArgDataclasses. data.render(as_json=True)now natively converts special Python objects into valid JSON strings without proprietary representations.- Replaced the separator-based path ID format (e.g.,
"1>011") indata.get_path_id()with a compact, separator-free uppercase hexadecimal encoding (e.g.,"1011","10C"). - Replaced runtime type tuples like
DataObjTTwith type guard functions likeis_data_obj(). - Changed
IndexIterabletoSeqOrSet[T]and addedis_seq_or_set(). - Removed raw
strandlist[float]fromRgbaandHslatype aliases, reserving them strictly for structured color representations (objects, tuples, lists of integers, and typed dicts). - Updated
RgbaDict,HslaDict, andHexaDictschemas to disallow explicitNonefor the optionalalphakey (alpha: NotRequired[float]andNotRequired[str]). rgba.blend()andhsla.blend()no longer accept color strings directly (raisingTypeError); color strings must be converted beforehand viato_rgba()orto_hsla().is_valid_rgba()andis_valid_hsla()now reject 4-element sequences withNoneas the fourth element and dictionaries withalpha: None.
- Replaced
- Renamed Functions & Methods:
color:text_color_for_on_bg()(andfg_for_on_bg()) →get_text_fg().luminance()→get_luminance().str_to_rgba()andstr_to_hsla()→extract_rgba()andextract_hsla()..values(),.dict(),.to_rgba(),.to_hsla(),.to_hexa()→.as_tuple(),.as_dict(),.as_rgba(),.as_hsla(),.as_hexa().
console:cls()→clear()(with fixed cross-platform terminal clearing on Windows and Unix).log_box_filled()andlog_box_bordered()→ unified intobox().supports_color()→has_color_support().ProgressBar:bar_format,limited_bar_format,set_bar_format()→format,limited_format,set_format().Throbber:throbber_format→format.
data&string:data.chars_count()→data.count_chars().string.single_char_repeats()→string.count_char_repeats().string.split_count()→string.chunk().string.change_tab_size()→string.change_tab_spaces().
- Parameters & Constants:
- Single-letter color channel parameters
r,g,b,h,s,l,a→red,green,blue,hue,sat,light,alpha. string.decompose(): parametercase_string→string.data.is_equal(): parametersdata1, data2→data_a, data_b.console.log_box_bordered(): parameterborder_charsnow takes a string of 11 characters instead of a tuple of 11 characters.console.box(): parameterw_full→width: int | Literal["full"] | None = None.console.pause_exit()and log presets (debug(),info(),done(),warn(),fail()): Replacedexit: boolandexit_code: intwithexit_code: int | None = None(Noneto not exit, or an integer exit code).console.exit(): Removed redundantexitboolean toggle parameter in favor of always exiting withexit_code: int, typed asNoReturn.
- Single-letter color channel parameters
- Removals:
- Removed
w_paddingparameter fromconsole.box()in favor of automatic contextual padding. - Removed
data.print()(usedata.render(…).print()). - Removed
serialize_bytes()anddeserialize_bytes()fromdata(byte serialization is now handled natively). - Removed
console.get_user()in favor ofsystem.get_username(). - Removed
reset_ansiparameter almost everywhere (appendS.RESETdirectly if needed). - Removed
format_linebreaksparameter fromconsole.log(). - Removed
FormattableString,AnyRgba,AnyHsla, andAnyHexatype aliases fromxulbux.base.types. - Removed
COLORclass presets andANSIclass fromxulbux.base.consts.
- Removed
v1.9
- Restructured CLI commands under a single
xulbux-libentry point:xulbux-lib– Shows library info.xulbux-lib fc(new) – Parses and renders a string's format codes as ANSI console output.
- Added a
.get()method toParsedArgDatafor safe index access on parsed argument values. - Added missing
__init__.pyfiles to thebaseandclisubpackages. - Fixed
ModuleNotFoundErrorcaused bymypyccompiling__init__.pyfiles, which broke subpackage imports. - Simplified CI workflows to use
pip's build isolation instead of manually specifying build dependencies. - Fixed a small bug in
ProgressBar, where it would only overwrite and not actually clear the previous line. - Added a new constant
ANSI.COLOR_VARIANTS_MAP, which contains all possible color variants that can be used in formatting. - Made it possible to also pass console default colors to
title_bg_colorinConsole.log(), instead of only custom RGBA or hex colors. - Added a new format key
link:…toFormatCodes, which allows you to create hyperlinks in the console output with the syntax[link:URL](display text).
BREAKING CHANGES:
- The
ANSI.COLOR_MAPconstant is now a set for better lookup performance, as the color order doesn't matter there. - All
Consolemethods that allow console default colors as input for their color parameters now actually validate the given color, raising an error if it's not valid. - The default for
box_bg_colorinConsole.log_box_filled()is now the console foreground color (None) instead ofbr:green.
- The compiled version of the library now includes the type stub files (
.pyi), so type checkers can thoroughly check types. - Made all type hints in the whole library way more strict and accurate.
- Removed leftover unnecessary runtime type checks in several functions throughout the whole library.
BREAKING CHANGES:
- All signatures that should use positional-only and keyword-only parameters now actually enforce that by using the
/and*syntax. - Renamed the
Spinnerclass from theconsolemodule toThrobber, since that name is closer to what it's actually used for. - Changed the name of the TypeAlias
DataStructuretoDataObjbecause that name is shorter and more general. - Changed both names
DataStructureTypesandIndexIterableTypestoDataObjTTandIndexIterableTTrespectively (TT= type tuple). - Made the return value of
String.single_char_repeats()always beintand notint | bool.
- Added a new class property
Console.encoding, which returns the encoding used by the console (e.g.,utf-8,cp1252, …). - Added multiple new class properties to the
Systemclass:is_linux– Whether the current OS is Linux or not.is_mac– Whether the current OS is macOS or not.is_unix– Whether the current OS is a Unix-like OS (Linux, macOS, BSD, …) or not.hostname– The network hostname of the current machine.username– The current user's username.os_name– The name of the operating system (e.g.,Windows,Linux, …).os_version– The version of the operating system.architecture– The CPU architecture (e.g.,x86_64,ARM, …).cpu_count– The number of CPU cores available.python_version– The Python version string (e.g.,3.10.4).
- Created two new type aliases:
ArgParseConfig– Matches the command-line-parsing configuration of a single argument.ArgParseConfigs– Matches the command-line-parsing configurations of multiple arguments, packed in a dictionary.
- Added a new attribute
flagto theArgDataTypedDict and theArgResultclass, which contains the specific flag that was found orNonefor positional args.
BREAKING CHANGES:
- Rewrote
Console.get_args()for different parsing functionality:- Flagged values are now also saved to lists, so only the
valuesattribute is used for all argument types. - The results of parsed command-line arguments are also no longer differentiated between regular flagged arguments and positional
"before"/"after"arguments. - The parameter
allow_spaceswas removed, and therefore a new parameterflag_value_sepwas added, which specifies the character(s) used to separate flags from their values.
This means flags can now only receive values when the separator is present (e.g.,--flag=valueor--flag = value).
- Flagged values are now also saved to lists, so only the
- Combined the custom TypedDict classes
ArgResultRegularandArgResultPositionalinto a single TypedDict classArgData, which is now used for all parsed command-line arguments. - Renamed the classes
ArgsandArgResulttoParsedArgsandParsedArgDatato better describe their purpose. - Renamed the attribute
is_positionaltois_poseverywhere so its name isn't that long.
- Added a new base module
base.decoratorswhich contains custom decorators used throughout the library. - Made
mypy_extensionsan optional dependency by wrapping all uses ofmypy_extensions.mypyc_attrin a custom decorator that acts as a no-op ifmypy_extensionsis not installed. - The methods from the
env_pathmodule that modify the PATH environment variable no longer sort all paths alphabetically but keep the original order to not mess with the user's intended PATH order. - Added a new TypeAlias
PathsListto thebase.typesmodule, which matches a list of paths as strings orpathlib.Pathobjects.
BREAKING CHANGES:
- Renamed the module
pathtofsand its main classPathtoFileSys, so you can better use it alongside the built-inpathlib.Pathclass without always needing to import one of them under an alias. - Renamed most
FileSysmethods to better describe their functionality:Path.extend()is nowFileSys.extend_path().Path.extend_or_make()is nowFileSys.extend_or_make_path().
- Renamed the parameter
use_closest_matchinFileSys.extend_path()andFileSys.extend_or_make_path()tofuzzy_match, since that name is more commonly used for that functionality. - Updated all library methods that work with paths to accept
pathlib.Pathobjects in addition to strings as path inputs. - Also, all library methods that return paths now return
pathlib.Pathobjects instead of strings.
- Added a new method
Color.str_to_hsla()to parse HSLA colors from strings. - Changed the default syntax highlighting for
Data.to_str()and therefore alsoData.print()to use console default colors. - Added the missing but needed dunder methods to the
ArgsandArgResultclasses and thergba,hslaandhexacolor objects for better usability and type checking. - Added three new methods to
Args:get()– Returns the argument result for a given alias or a default value if not found.existing()– Yields only the existing arguments as tuples of(alias, ArgResult).missing()– Yields only the missing arguments as tuples of(alias, ArgResult).
- Added a new attribute
is_positionaltoArgResult, which indicates whether the argument is a positional argument or not. - The
ArgResultclass now also has adict()method, which returns the argument result as a dictionary. - Added new properties
is_ttyandsupports_colorto theConsoleclass,hometo thePathclass, andis_winto theSystemclass. - Added the option to add format specifiers to the
{current},{total}and{percentage}placeholders in thebar_formatandlimited_bar_formatofProgressBar. - Finally fixed the
C901 'Console.get_args' is too complex (39)linting error by refactoring the method into its helper class. - Changed the string- and repr-representations of the
rgbaandhslacolor objects and newly implemented it for theArgsandArgResultclasses. - Made internal, global constants, whose values never change, into
Finalconstants for better type checking. - The names of all internal classes and methods are all no longer prefixed with a double underscore (
__), but a single underscore (_) instead. - Changed all methods defined as
@staticmethodto@classmethodwhere applicable to improve inheritance capabilities. - Adjusted the whole library's type hints to be way more strict and accurate, using
mypyas a static type checker. - Changed the class-property definitions to be defined via
metaclassand use@propertydecorators to make them compatible withmypyc. - Unnest all the nested methods in the whole library for compatibility with
mypyc. - The library is now compiled using
mypycwhen installing, which makes it run significantly faster. Benchmarking results:- Simple methods like data and color operations had a speed improvement of around 50%.
- Complex methods like console logging had a speed improvement of up to 230%!
BREAKING CHANGES:
- Renamed
Data.to_str()toData.render(), since that describes its functionality better (especially with the syntax highlighting option). - Renamed the constant
ANSI.ESCAPED_CHARtoANSI.CHAR_ESCAPEDfor better consistency with the other constant names. - Removed the general
PatternandMatchtype aliases from thebase.typesmodule (they are pointless since you should always use a specific type and not “type1 OR typeB”). - Removed the
_prefix from the parameter_syntax_highlightinginData.render(), since it's no longer just for internal use.
- Added a new class
LazyRegexto theregexmodule, which is used to define regex patterns that are only compiled when they are used for the first time. - Removed unnecessary character escaping in the precompiled regex patterns in the
consolemodule. - Removed all the runtime type checks that can also be checked using static type-checking tools, since you're supposed to use type checkers in modern Python anyway, and to improve performance.
- Renamed the internal class method
FormatCodes.__config_console()toFormatCodes._config_console()to make it callable but still indicate that it's internal. - Fixed a small bug where
Console.log_box_…()would crash when calling it without providing any*values(content for inside the box).
BREAKING CHANGES:
The arguments when calling
Console.get_args()are no longer specified in a single dictionary, but now each argument is passed as a separate keyword argument.
You can still use a dictionary just fine by simply unpacking it with**, like this:pythonConsole.get_args(**{"arg": {"-a", "--arg"}})Replaced the internal
_COMPILEDregex pattern dictionaries withLazyRegexobjects so it won't compile all regex patterns on library import, but only when they are used for the first time, which improves the library's import time.Renamed the internal
_COMPILEDregex pattern dictionaries to_PATTERNSfor better clarity.Removed the import of the
ProgressBarclass from the__init__.pyfile since it's not an important main class that should be imported directly.Renamed the constant
CLRtoCLI_COLORSand the constantHELPtoCLI_HELPin thecli.helpmodule.Changed the default value of the
strip_spacesparameter inRegex.brackets()fromTruetoFalse, since this is more intuitive behavior.
- Unified the module and class docstring styles throughout the whole library.
- Moved the protocol
ProgressUpdaterfrom theconsolemodule to thetypesmodule. - Added throttling to the
ProgressBarupdate methods to impact the actual process' performance as little as possible. - Added a new class
Spinnerto theconsolemodule, which is used to display a spinner animation in the console during an ongoing process.
BREAKING CHANGES:
- Made the value input into the parameters
bar_formatandlimited_bar_formatofProgressBarbe a list/tuple of strings instead of a single string so the user can define multiple formats for different console widths. - Added a new parameter
sep: str = " "to theProgressBarclass, which is used to join multiple bar-format strings. - Renamed the class property
Console.whtoConsole.size, since it describes the property better. - Renamed the class property
Console.usrtoConsole.user, since it describes the property better. - Added missing type checking to methods in the
pathmodule.
- Standardized the docstrings for all public methods in the whole library to use the same style and structure.
- Replaced left over single quotes with double quotes for consistency.
- Fixed a bug inside
Data.remove_empty_items(), where types apart from strings were passed toString.is_empty(), which caused an exception. - Refactored/reformatted the code of the whole library to introduce clearer code structure with more room to breathe.
- Made the really complex regex patterns in the
Regexclass all multiline for better readability. - Added a new internal method
Regex._clean(), which is used to clean up the regex patterns defined as multiline strings. - Moved custom exception classes to their file
base/exceptions.pyso the user can easily import them all from the same place. - Moved custom types to their file
base/types.pyso the user can easily import them all from the same place. - Removed unnecessary duplicate code in several methods throughout the library.
- Introduced some minor performance improvements in a few methods that might be called very frequently in a short time span.
- Added a small description to the docstrings of all modules and their main classes.
BREAKING CHANGES:
- The
find_argsparameter from the methodConsole.get_args()now only accepts sets for the flags instead of lists/tuples since the order of flags doesn't matter and sets have better performance for lookups. - Added missing type checking to all public methods in the whole library, so now they will all throw errors if the parameters aren't of the expected type.
- Removed the second definitions of constants in with lowercase names in the
ANSIclass inside theconstsmodule, so now you can only access them with their uppercase names (e.g.,ANSI.CHARinstead ofANSI.char).
v1.8
- Made the help command
xulbux-helpuse console default colors so it fits the user's console theme. - Changed the default
box_bg_colorinConsole.log_box_filled()fromgreentobr:green. - Fixed a bug in all methods of
FormatCodes, where as soon as you used more than a single modifier format code (e.g.,[ll]or[++]), it was treated as invalid and ignored. - Added a new method
FormatCodes.escape()which will escape all valid formatting codes in a string. - Again refactored the whole
CHANGELOG.mdto use actual sentences and added aBREAKING CHANGESsection to more clearly highlight breaking changes.
BREAKING CHANGES:
- Removed the
*cand*colorformatting codes, since the user should just use the codedefaultto achieve the same instead. - Renamed the method
FormatCodes.remove_formatting()toFormatCodes.remove().
- Adjusted
Regex.hsla_str()to not include optional degree (°) and percent (%) symbols in the captured groups. - Fixed that
Regex.hexa_str()couldn't match hex colors anywhere inside a string, but only if the whole string was just the hex color. - Added
_ArgResultRegularand_ArgResultPositionalTypedDict classes for better type hints inArgs.dict()andArgs.items()methods.
BREAKING CHANGES:
- The method
Console.get_args()no longer tries to convert found arg values to their respective types since that caused too many unwanted wrong type conversions. ArgResultnow has separate properties for different argument types to improve type safety and eliminate the need for type casting when accessing argument values:value: Optional[str]– For regular flagged arguments.values: list[str]– For positional"before"/"after"arguments.
- Adjusted the look of the prompts and inputs of the
System.check_libs()method. - Added a new parameter to
System.check_libs():
missing_libs_msgs: tuple[str, str] = (…)– Two messages:
The first one is displayed when missing libraries are found.
The second one is the confirmation message before installing missing libraries. - Adjusted error messages throughout the whole library to all be structured about the same.
- Fixed a small bug in
FormatCodes.__config_console(), where it would cause an exception because it tried to configure Windows-specific console settings on non-Windows systems. - The
Console.get_args()method will now treat everything as values (even if it starts with-or--) unless it's specified in thefind_argsparameter. - Added two new parameters to all the
Console.log()presets:
exit_code: int = 0– The exit code to use ifexitis true.reset_ansi: bool = True– Whether to reset all ANSI formatting after pausing/exiting or not.
- Made the type hints and value checks for
Console.get_args()more strict. - You can now insert horizontal rules inside a
Console.log_box_bordered()by putting{hr}in the text. - Made it possible to also update the title within a
ProgressBar.progress_context()using the returned callable with the new kwarglabel.
BREAKING CHANGES:
- Reordered the parameters of
Console.pause_exit()to be more logical.
- The client command
xulbux-helpnow tells you that there's a newer version of the library available if you're not using the latest version. - Added two new parameters to
Console.input():default_val: Optional[T] = None– The default value to return if the input is empty.output_type: type[T] = str– The type (class) to convert the input to before returning it.
- Added a new class
ProgressBarto theconsolemodule. - Made a small performance improvement in
FormatCodes.to_ansi(). - Added missing docstrings to several public class variables.
- Added the missing tests for methods in the
consolemodule. - Added a test for the last two modules that didn't have tests until now:
regexandsystem.
BREAKING CHANGES:
- Spaces between a format code and the auto-reset brackets are no longer allowed, so
[red]␣(text)will not be automatically reset and output as␣(text).
- Fixed a critical bug that caused the package to not install properly and make the whole library not work.
- Fixed several small bugs regarding the tabs and text wrapping inside
Console.log(). - Added two new parameters to
Console.log():title_px: int = 1– The horizontal padding (in chars) to the title (iftitle_bg_coloris set).title_mx: int = 2– The horizontal margin (in chars) to the title.
BREAKING CHANGES:
- Renamed the parameter
_console_tabsizefrom the methodConsole.log()totab_size, and it will now just set the size for the log directly instead of specifying what the console's tab size is.
- New options for the parameter
find_argsfrom the methodConsole.get_args():
Previously, you could only input a dictionary with items like"alias_name": ["-f", "--flag"]that specify an arg's alias and the flags that correspond to it.
New, instead of flags, you can also once use the literal"before"and once"after", which corresponds to all non-flagged values before or after all flagged values. - Changed the default
default_colorfor allConsoleclass input methods toNone. - Now
promptfromConsole.pause_exit()also supports custom formatting codes and the method new pauses per default (without exiting).
BREAKING CHANGES:
- The method
Console.restricted_input()now returns an empty string instead ofNoneif the user didn't input anything. - Completely rewrote
Console.restricted_input(), so now it's actually usable, and renamed it to justConsole.input(). - Removed method
Console.pwd_input(), since you can now simply useConsole.input(mask_char="*")instead, which does the same thing. - Removed the CLI command
xx-help, since it was redundant because there's already the CLI commandxulbux-help. - Renamed the previously internal module
_consts_toconstsand made it accessible viafrom xulbux.base.consts import …, since you should be able to use library constants without them being «internal». - Removed the
xx_from all the library modules since it's redundant, and without it, the imports look more professional and cleaner. - The constants from inside the
constsmodule are now all uppercase (except the class methods) to make clear that they're constants. - Removed the wildcard imports from the
__init__.pyfile, so now you can only access the main classes directly withfrom xulbux import …and for the rest you have to import the specific module first.
v1.7
- Added a new parameter to the methods
Console.log_box_filled()andConsole.log_box_bordered():
indent: int = 0– The indentation of the box (in chars). - Fixed a bug in
Console.log_box_filled()where the box background color would sometimes not stop at the box's edge but would continue to the end of the console line.
BREAKING CHANGES:
- Removed the parameter
title_bg_colorfrom theConsole.log()preset methods since that is part of the preset and doesn't need to be changed by the user.
- The
Console.w,Console.handConsole.whclass properties now return a default size if there is no console, instead of throwing an error. - It wasn't actually possible to use default console colors (e.g.,
"red","green", …) for the color parameters inConsole.log()so that option was completely removed again. - Upgraded the speed of
FormatCodes.to_ansi()by adding the internal ability to skip thedefault_colorvalidation. - Fixed type hints for the whole library.
- Fixed a small bug in
Console.pause_exit(), where the key pressed to unpause wasn't suppressed, so it was written into the next console input after unpausing.
- Resolved an issue with the
Color.is_valid_…()andColor.is_valid()methods, where you were unable to input any color without a type mismatch. - Added a new method
Console.log_box_bordered(), which does the same asConsole.log_box_filled(), but with a border instead of a background color. - The module
xx_format_codesnow treats the[*]to-default-color-reset as a normal full reset when nodefault_coloris set instead of just counting it as an invalid format code. - Fixed a bug where entering a color as a hex integer in the color parameters of the methods
Console.log(),Console.log_box_filled()andConsole.log_box_bordered()would not work, because it was not properly converted to a format code. - You can now use default console colors (e.g.,
"red","green", …) for the color parameters inConsole.log(). - The methods
Console.log_box_filled()andConsole.log_box_bordered()no longer right-strip spaces, so you can make multiple log boxes the same width by adding spaces to the end of the text.
BREAKING CHANGES:
- Renamed the method
Console.log_box()toConsole.log_box_filled().
- Fixed a small bug in
Console.log()where empty line breaks were removed. - Corrected and added missing type hints for the whole library.
- Fixed possibly unbound variables for the whole library.
- Updated the client command
xulbux-help.
v1.6
- Added a new parameter to the methods
FormatCodes.remove_ansi()andFormatCodes.remove_formatting():
_ignore_linebreaks: bool = False– Whether to include line breaks in the removal positions or not. - Added a new parameter to method
Color.luminance()and to the.grayscale()method of all color types:method: str = "wcag2"– The luminance calculation method to use. - Added a new parameter to the method
File.rename_extension():full_extension: bool = False– Whether to treat everything behind the first.as the extension or everything behind the last.. - Fixed a small bug in
Console.log_box()where the leading spaces were removed from the box content. - You can now assign default values to args in
Console.get_args().
BREAKING CHANGES:
- Changed the parameters in
Json.create():new_file: str = "config"is now the first parameter andcontent: dictthe second one.new_file: str = "config"is now calledjson_file: strwith no default value.
- The methods
Json.update()andData.set_value_by_path_id()now take a dictionary as theupdate_valuesparameter instead of a list of strings. - Renamed parameter
correct_pathinPath.extend()and parametercorrect_pathsinFile.extend_or_make_path()touse_closest_match, since this name describes its functionality better. - Moved the method
extend_or_make_path()from thexx_filemodule to thexx_pathmodule and renamed it toextend_or_make().
- Made it possible to escape formatting codes by putting a slash (
/or\\) at the beginning inside the brackets (e.g.,[/red]). - New methods for
Args(the returned object fromConsole.get_args()):- The
len()function can now be used onArgs(the returned object fromConsole.get_args()). - The
Argsobject now also has the dictionary-like methods.keys(),.values()and.items(). - You can also get the args as a dict with the
.dict()method. - You can now use the
inoperator onArgs.
- The
- New methods for
ArgResult(a single arg-object from insideArgs):- You can now use the
bool()function onArgResultto directly see if the arg exists.
- You can now use the
- The methods
FormatCodes.remove_ansi()andFormatCodes.remove_formatting()now have a second parameterget_removals: bool = False:
If this parameter is true, in addition to the cleaned string, a list of tuples will be returned, where a tuple contains the position of the removed formatting/ANSI code and the removed code. - Fixed a bug in the line wrapping in all logging methods from the
xx_consolemodule. - Added a new parameter to the method
Console.get_args():
allow_spaces: bool = False– Whether to take spaces as separators of arg values or as part of an arg value.
- Made the static method
System.is_elevated()into a class property, which now can be accessed asSystem.is_elevated. - The method
File.create()now throws a customSameContentFileExistsErrorexception if a file with the same name and content already exists. - Added a bunch more docstrings to class properties and library constants.
BREAKING CHANGES:
- Restructured the object returned from
Console.get_args():
Before, you accessed an arg's result withargs["<arg_alias>"]["value"]andargs["<arg_alias>"]["exists"].
Now, you can directly access the result withargs.<arg_alias>.valueandargs.<arg_alias>.exists. - Made the method
Path.get(cwd=True)orPath.get(base_dir=True)into two class properties, which now can be accessed asPath.cwdandPath.script_dir.
- Added a new method
Console.multiline_input(). - Added two new parameters to the method
Console.log_box():
w_padding: int = 2– The horizontal padding (in chars) to the box content.w_full: bool = False– Whether to make the box be the full console width or not.
- Fixed a small bug in
Data.print()where two parameters passed toData.to_str()were swapped, which caused an error. - The method
Data.print()now per default syntax highlights the console output:
The syntax highlighting colors and styles can now be customized via the new parametersyntax_highlighting: dict[str, str] = {…}. - Added two new methods,
Data.serialize_bytes()andData.deserialize_bytes(). - Made the method
String.to_type()be able to also interpret and convert large, complex structures. - Added the new parameter
strip_spaces: bool = Trueto the methodRegex.brackets()which makes it possible to not ignore spaces around the content inside the brackets. - Adjusted the
Console.log_box()method so the box background can't be reset to nothing anymore. - Added a new parameter to
Console.log()(and therefore also to everyConsole.log()preset):
format_linebreaks: bool = True– When true, indents the text after every line break to the level of the previous text.
BREAKING CHANGES:
- Restructured the
_consts_library constants to use@dataclassclasses (and simpler structured classes) as much as possible. - Renamed the
DEFAULTclass from the_consts_toCOLOR, whose colors are now directly accessible as variables (e.g.,COLOR.red) and not through dictionary keys. - Changed the methods
Console.w(),Console.h(),Console.wh()andConsole.user()to modern class properties instead:
Console.w– Current console columns (in text characters).Console.h– Current console lines.Console.wh– A tuple with the console size as (columns, lines).Console.usr– The current username.
- Now the method
FormatCodes.to_ansi()automatically converts the parameterstringto astrif it isn't one already. - Added a new method
FormatCodes.remove_codes(). - Added a new method
FormatCodes.remove_ansi(). - Added a new method
Console.log_box(). - Changed the default values of two parameters in the
Console.log()method and every log preset:
start: str = "\n"changed tostart: str = ""end: str = "\n\n"changed toend: str = "\n"
- Added the parameters
start: str = "",end: str = "\n"anddefault_color: rgba | hexa = DEFAULT.color["cyan"]toConsole.restricted_input()andConsole.pwd_input().
- Fixed a critical bug where the library could not be imported after the last update due to an issue in
xx_format_codes.
- Fixed a small bug in
xx_format_codes:
Inside print strings, if there was a'or"inside an auto-reset formatting (e.g.,[u](there's a quote)), that caused it to not be recognized as valid and therefore not be automatically reset.
Now this is fixed, and auto-reset formatting works as expected. - Added a new parameter
ignore_in_strings: bool = TruetoRegex.brackets():
If this parameter is true and a bracket is inside a string (e.g.,'…'or"…"), it will not be counted as the matching closing bracket. - Removed
lru_cachefrom thexx_format_codesmodule's internal methods since it was unnecessary. - Adjusted
FormatCodes.__config_console()so it can only be called once per process.
- Added a new method
elevate()toxx_system, which is used to request elevated privileges. - Fixed a bug in
rgba(),hsla()andhexa():
Previously, when initializing a color with the alpha channel set to0.0(100% transparent), it was saved correctly, but when converted to a different color type or when returned, the alpha channel got ignored, just like if it wasNoneor1.0(opaque).
Now when initializing a color with the alpha channel set to0.0, this doesn't happen, and when converted or returned, the alpha channel is still0.0. - Huge speed and efficiency improvements in
xx_color, due to the newly added option to initialize a color without validation, which saves time when initializing colors when we know that the values are valid. - Added a new parameter
reset_ansi: bool = FalsetoFormatCodes.input():
If this parameter is true, all formatting will be reset after the user confirms the input and the program continues.
BREAKING CHANGES:
- Moved the method
is_admin()fromxx_consoletoxx_system. - Method
hex_int_to_rgba()fromxx_colornow returns anrgba()object instead of the separate valuesr,g,banda.
- Changed the parameters in
File.make_path():
Previously there were the parametersfilename: strandfiletype: str = ""wherefilenamedidn't have to have the file extension included, as long as thefiletypewas set.
Now these parameters have become one parameterfile: strwhich is the file with the file extension. - Removed all line breaks and other Markdown formatting from docstrings, since not all IDEs support them.
BREAKING CHANGES:
- Changed the order of the parameters in
File.create():
Until now the parametercontent: str = ""was the first parameter andfile: str = "".
Now the parameterfile: str = ""is the first parameter andcontent: str = ""is the second. - Renamed
File.make_path()to a more descriptive nameFile.extend_or_make_path()and adjusted the usages ofFile.create()andFile.make_path()insidexx_jsonaccordingly.
- Fixed a small bug in
to_camel_case()in thexx_stringmodule:
Previously, it would return only the first part of the decomposed string.
Now it correctly returns all decomposed string parts, joined in CamelCase.
v1.5
- Fixed bugs in method
to_ansi()in modulexx_format_codes:
- The method always returned an empty string because the color validation was broken, and it would identify all colors as invalid.
Now the validationColor.is_valid_rgba()andColor.is_valid_hexa()are fixed, and now, if a color is identified as invalid, the method returns the original string instead of an empty string. - Previously the method
to_ansi()couldn't handle formats inside[]because everything inside the brackets was recognized as an invalid format.
Now you can use formats inside[](e.g.,"[[red](Red text [b](inside) square brackets!)]").
- The method always returned an empty string because the color validation was broken, and it would identify all colors as invalid.
- Introduced a new test for the
xx_format_codesmodule. - Fixed a small bug in the help client command:
Added back the default text color.
- Added method
String.is_empty()to check if the string is empty. - Added method
String.escape()to escape special characters in a string. - Introduced a new test for
xx_data(all methods). - Added docstrings to all the methods in
xx_data. - Made all the methods from
xx_datawork with all the types of data structures (lists, tuples, sets, frozensets, and dicts). - Added method
EnvPath.remove_path(). - Introduced a new test for
xx_env_vars(all methods). - Added a
hexa_str()preset to thexx_regexmodule. - Introduced a new test for the methods from the
Colorclass inxx_color.
BREAKING CHANGES:
- Renamed the library from
XulbuXtoxulbuxfor better naming conventions. - Renamed the module
xx_cmdand its classCmdtoxx_consoleandConsole. - Renamed the module
xx_env_varsand its classEnvVarstoxx_env_pathandEnvPath.
- Change the testing modules to be able to run together with the library
pytest. - Added formatting checks, using
black,isortandflake8. - Added the script (command)
xx-helporxulbux-help. - Structured
Cmd.restricted_input()a bit nicer so it appears less complex. - Corrected code after
Lint with flake8formatting suggestions. - Added additional tests for the custom color types.
- Updated the whole
xx_format_codesmodule for more efficiency and speed.
BREAKING CHANGES:
- Moved the
help()function to the file_cli_.py, because that's where all the scripts are located (and renamed it tohelp_command()). - Moved the method
normalize_spaces()toxx_string.
- Moved the whole library to a separate repository: python-lib-xulbux
- Updated all connections and links correspondingly.
- Added methods to get the width and height of the console (in characters and lines):
Cmd.w() -> int– How many text characters the console is wide.Cmd.h() -> int– How many lines the console is high.Cmd.wh() -> tuple[int, int]– A tuple with width and height.
- Added the method
split_count(string, count) -> list[str]toxx_string. - Added docstrings to every method in
xx_string. - Updated the
Cmd.restricted_input()method to be able to:- paste text from the clipboard,
- select all text to delete everything at once,
- write and backspace over multiple lines and
- support custom formatting codes in the prompt.
- Added required non-standard libraries to the project file.
- Added more metadata to the project file.
- Added a new method
normalize_spaces(code) -> strtoCode. - Added new docstrings to
xx_codeandxx_cmd. - Added a custom
input()method toCmd, which lets you specify the allowed text characters the user can type, as well as the minimum and maximum length of the input. - Added the method
pwd_input()toCmd, which works just like theCmd.restricted_input()but masks the input characters with*. - Restructured the whole library's imports so the custom types won't get displayed as
Anywhen hovering over a method/function. - Fixed a bug when trying to get the base directory from a compiled script (EXE):
Would previously get the path to the temporary extracted directory, which is created when running the EXE file.
Now it gets the actual base directory of the currently running file.
BREAKING CHANGES:
- Made the
blend()method from all the color types modify theselfobject in addition to returning the result.
- Added the default text color to the
_consts_.pyso it's easier to change it (and used it in the library). - Added several other default colors to the
_consts_.py(and used them in the library). - Refactored the whole library's code after the PEPs and The Zen of Python 🫡:
- Changed the indent to 4 spaces.
- No more inline control statements.
- Added new methods to
Color:
rgba_to_hex(r, g, b, a) -> inthex_to_rgba(hex_int) -> tupleluminance(r, g, b, precision, round_to) -> float | int
- Fixed the
grayscale()method ofrgba(),hsla()andhexa():
The method would previously just return the color, fully desaturated (not grayscale).
Now this is fixed, and the method uses the luminance formula to get the actual grayscale value. - All the methods in the
xx_colormodule now support hex integers (e.g.,0x8085FFinstead of only strings:"#8085FF""0x8085FF").
BREAKING CHANGES:
- Restructured the values in
_consts_.py.
- New parameter
correct_path: boolinPath.extend(): This makes sure that typos in the path will only be corrected if this parameter is true. - Fixed a bug in
Path.extend(), where an empty string was taken as a valid path for the current directory./. - Fixed color validation bug:
Color.is_valid_rgba()andColor.is_valid_hsla()would not accept an alpha channel ofNone.
Color.is_valid_rgba()was still checking for an alpha channel from0to255instead of0to1. - Fixed a bug for
Color.has_alpha():
Previously, it would returnTrueif the alpha channel wasNone.
Now in such cases it will returnFalse.
- Now all methods in
xx_colorsupport both hex prefixes (#and0x). - Added the default hex prefix to
_consts_.py. - Fixed a bug when initializing a
hexa()object:
Would throw an error, even if the color was valid.
BREAKING CHANGES:
- Renamed all library files for a better naming convention.
- Added a
__help__.pyfile, which will show some information about the library and how to use it when it's run as a script or when thehelp()function is called. - Added a lot more metadata to the library:
__version__(was already added in update v1.4.2)
__author__
__email__
__license__
__copyright__
__url__
__description__
__all__
BREAKING CHANGES:
- Split all classes into separate files so users can download only parts of the library more easily.
v1.4
Path.extend(rel_path) -> abs_pathnow also extends system variables like%USERPROFILE%and%APPDATA%.- Removed unnecessary parts when checking for missing required libraries.
- You can now get the library's current version by accessing the attribute
XulbuX.__version__.
- Added methods to each color type:
is_grayscale() -> selfis_opaque() -> self
- Added additional error checking to the color types.
- Made error messages for the color types clearer.
- Updated the
blend(other, ratio)method of all color types to use additive blending except for the alpha channel. - Fixed problem with method chaining for all color types.
- Massive update to the custom color types:
- Now all type methods support chaining.
- Added new methods to each type:
lighten(amount) -> self
darken(amount) -> self
saturate(amount) -> self
desaturate(amount) -> self
rotate(hue) -> self
invert() -> self
grayscale() -> self
blend(other, ratio) -> self
is_dark() -> bool
is_light() -> bool
with_alpha(alpha) -> self
complementary() -> self
v1.3
- Now the alpha channel will be rounded to a maximum of 2 decimals if converting from
hexa()torgba()orhsla().
- Fixed the custom types
rgba(),hsla()andhexa():
rgba():
Fixedto_hsla()andto_hexa().hsla():
Fixedto_rgba()andto_hexa().hexa():
Fixedto_rgba()andto_hsla().
- Fixed methods from the
Colorclass:
Color.has_alpha()
Color.to_rgba()
Color.to_hsla()
Color.to_hexa() - Set default value for parameter
allow_alpha: booltoTruefor methods:
Color.is_valid_rgba()
Color.is_valid_hsla()
Color.is_valid_hexa()
Color.is_valid()
v1.2
- Added more info to the
README.mdas well as additional links. - Adjusted the structure inside
CHANGELOG.mdfor a better overview and readability.
BREAKING CHANGES:
- Renamed the class
rgb()torgba()to communicate more clearly that it supports an alpha channel. - Renamed the class
hsl()tohsla()to communicate more clearly that it supports an alpha channel.
- Added project links to the Python-project-file.
- Made some
CHANGELOG.mdimprovements. - Improved
README.md.
- Fixed a bug in the method
Path.get(base_dir=True):
Previously, settingbase_dirtoTruewould not return the actual base directory or even cause an error.
Settingbase_dirtoTruenow will return the actual base directory of the current program (except if not running from a file).
- New method in the
Pathclass:
Path.remove()
v1.1
BREAKING CHANGES:
- Corrected the naming of classes to comply with Python naming standards.
- Added support for all OSes to the OS-dependent methods.
- Fixed the
Cmd.cls()method:
There was a bug where only on Windows 10, the ANSI formats weren't cleared.
- Added links to the
CHANGELOG.mdandREADME.mdfiles.
- Changed the default value of the parameter
compactness: intin the methodData.print()to1instead of0.
- Adjusted the library's description.
- Made it possible to also auto-reset the color and not only the predefined formats, using the auto-reset format (
[format](Automatically resetting)).
v1.0
Added a library description, which gets shown if the library base import is run directly.
Made it possible to escape an auto-reset format (
[format](Automatically resetting)) with a slash, so you can still have()brackets behind a[format]:pythonFormatCodes.print("[u](Automatically resetting) following text")Prints:
Automatically resetting following textpythonFormatCodes.print("[u]/(Automatically resetting) following text")Prints:
(Automatically resetting) following text
- Added an
input()method to theFormatCodesclass so you can make pretty-looking input prompts. - Added a warning for no network connection when trying to install missing libraries.
- Improved XulbuX library importing:
Checks for missing required libraries and gives you the option to directly install them, if there are any. - Fixed issue where configuration file wasn't created and loaded correctly.
BREAKING CHANGES:
- Moved constant variables into a separate file.
- Fixed
f-stringissues for Python 3.10:- Not making use of the same quotes inside f-strings anymore.
- No backslash escaping in f-strings.
At initial release, the library
# General library:
import XulbuX as xx
# Custom types:
from XulbuX import rgb, hsl, hexa| Features | class, type, function, … |
|---|---|
| Custom Types: | rgb(int, int, int, float)hsl(int, int, int, float)hexa(str) |
| Directory Operations | xx.Dir |
| File Operations | xx.File |
| JSON File Operations | xx.Json |
| System Actions | xx.System |
| Manage Environment Vars | xx.EnvVars |
| CMD Log And Actions | xx.Cmd |
| Pretty Printing | xx.FormatCodes |
| Color Operations | xx.Color |
| Data Operations | xx.Data |
| String Operations | xx.String |
| Code String Operations | xx.Code |
| Regex Pattern Templates | xx.Regex |