Package: junkpy
JunkpyJunkpy is a Python library for processing Junk configuration files.Junk File FormatJunk is a file format for configuration files that extends the capabilities of the standard JSON format by introducing additional options and features.Junk Features OverviewUnquoted Keys:{unquoted_key:"value",another_unquoted_key:42}Trailing Commas in Objects and Arrays:{"key1":"value1","key2":"value2","key3":"value3",}["item1","item2","item3",]Implicit null values:{"null_key":null,"empty_value":,}Comments:{"key1":"value1",#Thisisacommentaboutkey1"key2":"value2",#Thisisacommentaboutkey2"key3":"value3"#Thisisacommentaboutkey3}Type conversion and custom types:{"int_value":(int)"123","float_value":(float)"3.14","string_value":(string)456,"chained_types_value":(string)(int)99.99,"custom_type_value":(custom_type)"abcd","array_with_different_types":[(int)55.6,(float)88,(string)1234,]}Arguments on type conversion:{"custom_type_value1":(custom_type,arg1=33,arg2="1234")333,"custom_type_value2":(custom_type,arg1=(int)99.5,arg2=(string)5678)444,}InstallationYou can install Junkpy usingpip. Open your terminal and run the following command:pipinstalljunkpyUsageTo use the Junkpy library in your Python projects, follow these steps:Import theJunkParserclass from thejunkpymodule:fromjunkpyimportJunkParserCreate an instance of theJunkParserclass:junk_parser=JunkParser()Load data from a file using theload_file()method:data=junk_parser.load_file("file.junk")Replace"file.junk"with the path to your own file.Theload_file(file_path)method reads the contents of the specified file and processes it using the Junk parser.
Additional methods such asloads(string)andload(fp)parse data from a string or a file-like object respectively.Custom Type ProcessorsThejunkpylibrary allows you to create custom type processors to manage how a Junk file is parsed. Here's an example of how you can create one:fromjunkpyimportJunkParser,JunkTypeProcessorclassBoundedValueTypeProcessor(JunkTypeProcessor):CLASS=float# Output classKEYWORD="bounded-value"# Custom type keyworddefload(self,value,**kwargs):obj=self.CLASS(value)if"min"inkwargs:obj=max(kwargs["min"],obj)if"max"inkwargs:obj=min(kwargs["max"],obj)returnobj# Instantiate the Junk parser with a list of custom type processorsjunk_parser=JunkParser([BoundedValueTypeProcessor])A basic type processor class requires definingCLASSandKEYWORDattributes andloadmethod.CLASS: Defines the output type of the processed value.Type checking is performed after the value has been processed.KEYWORD: A string that will trigger this type processor when parsing data.`load: An instance method aimed at processing and returning a value given its parameters:self: Reference to the own type processor instance.value: The value to be processed. This object could be of any type.**kwargs: Keyword arguments received from data being parsed.Every type processor contains a shared property calledmetadatawhich can be accessed insideloadmethod. This property stores the following data:file_path: Path of the current file being parsed, if any, otherwiseNone.Themetadatacan also be used to store data and share it across different type processors.Retrieve the current parser instance from theparserproperty of type processors. This allows parsing data recursively while processing is ongoing.By including your custom type processor during the parser's initialization, you enable the parser to recognize and apply the specified modifications when loading files.Note: Not all type conversions in Junkpy can be initialized with a null value. For example, when anullvalue is converted to the type(string), a Python string object with the value"None"will be created. However, if the type is(int), it will result in an error sincenullcannot be converted to an integer. It's important to exercise caution when using type conversions and ensure they are compatible with null values.Extending the Parser ClassJunkpy provides the flexibility to extend and customize the parsing process by subclassing theJunkParserclass and overriding two extensible methods:before_parsingandafter_parsing. These methods allow you to perform additional actions or processing steps before and after parsing Junk files.Thebefore_parsingmethod is called before the parsing of a Junk file begins. It receivesmetadata, which contains information about the file being parsed. You can use this method to perform any pre-processing tasks or set up configurations specific to your needs.classMyCustomParser(JunkParser):defbefore_parsing(self,metadata:JunkMetadata):# Perform pre-processing tasks or configuration setup hereTheafter_parsingmethod is called after the parsing of a Junk file is complete. It receivesmetadata, which contains information about the parsed file, andparsed_data, which is the resulting parsed data as an object. You can use this method to perform any post-processing tasks, validation, or additional actions on the parsed data.classMyCustomParser(JunkParser):defafter_parsing(self,metadata:JunkMetadata,parsed_data:object)->object:# Perform post-processing tasks or validation on parsed_data here# Return the modified parsed_datareturnparsed_dataBuilt-in typesTypeReturn ValueSupported ValuesExample InitializationstringstrAny string value(string) "Hello, World!"regexre.PatternValid regular expression patterns(regex) "[A-Za-z]+[0-9]*"envstrEnvironment variable names/expresions(env) "$HOME"pathpathlib.PathFile system paths (environment variables supported on path string)(path) "$HOME/path/to/file.txt"intintInteger values(int) 123binintBinary integer values(bin) "10101"octalintOctal integer values(octal) "123"hexintHexadecimal integer values(hex) "1234567890ABCDEF"complexcomplexComplex number values(complex) "3+4j"floatfloatFloating-point values(float) 3.14159decimaldecimal.DecimalDecimal values(decimal) "3.14"boolboolBoolean values(bool) truesetsetSets of values(set) [1, 2, 3]timestampdatetime.datetimeUnix timestamp values(timestamp) 1623345600timedeltadatetime.timedeltaTime differences in seconds(timedelta) 60Time differences in a list [DAYS, SECONDS, MICROSECONDS, MILLISECONDS, MINUTES, HOURS, WEEKS](timedelta) [5, 10, 200, 150, 3, 4, 8]Time differences in a dict with keyword arguments as keys(timedelta) {"days": 1, "seconds": 3600}timedatetime.timeTime values in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM](time) "12:30:45"Time values in a list [HOUR, MINUTE, SECOND, MICROSECOND](time) [12, 30, 45, 152]Time values in a dict with keyword arguments as keys(time) {"hour": 12, "minute": 30, "second": 45}datedatetime.dateDate values in ISO 8601 format, YYYY-MM-DD(date) "2021-07-10"Date values in a list [YEAR, MONTH, DAY](date) [2021, 7, 10]Date values in a dict with keyword arguments as keys(date) {"year": 2021, "month": 7, "day": 10}datetimedatetime.datetimeDate and time values in ISO 8601 format, YYYY-MM-DD [HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM](datetime) "2021-07-10 12:30:45"Date and time values in a list [YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, MICROSECOND](datetime) [2021, 7, 10, 12, 30, 45, 580]Date and time values in a dict with keyword arguments as keys(datetime) {"year": 2021, "month": 7, "day": 10, "hour": 12, "minute": 30, "second": 45}ContributingContributions to Junkpy are welcome! If you encounter any issues, have suggestions for improvements, or would like to add new features, please feel free to submit a pull request.To contribute to Junkpy, follow these steps:Fork the repository.Create a new branch for your feature or bug fix.Implement your changes.Write tests to ensure the correctness of your code.Commit and push your changes to your forked repository.Open a pull request and provide a detailed description of your changes.LicenseJunkpy is released under theGNU GPLv3license. You are free to use, modify, and distribute this library as per the terms of the license.SupportIf you need assistance or have questions about Junkpy, please feel free toopen an issueon the GitHub repository. We'll be happy to assist you.