To keep the codebase maintainable and readable, all code is developed using a similar coding style. It ensures:
- the code is easy to maintain and understand.
- It is really important that the original developer is able to come back to code 5 months later and still quickly understands what the code is supposed to be doing.
- For other people that want to contribute, to quickly understand the code.
- that every developer can, largely, expect the same coding style across the entire code base.
Having a unified style makes it much easier to maintain the our projects. That means that every developer should be able to make changes in any file in the log2timeline organization without worrying about different code styles.
Log2Timeline's style is based on the the Google Python Style Guide, with specific variations and expansion spelled out in the sections below.
All new log2timeline code should be compatible with Python 3.10+.
- Indent your code blocks with 4 spaces
- In the case of a hanging indent, use 4 spaces.
Tip: use the Python formatting tool black to help ensure code has the appropriate indentation
- 88 characters
Tip: use the Python formatting tool black to help ensure code has the appropriate number of empty lines
- Use full English words everywhere. For example, use Event not Evt and Description not Desc.Python-3-Guide.md
- Acronyms and initialisms should be preserved, such as HTMLParser and not HtmlParser.
- Use "cls" as the name of the class variable in preference to "klass"
- Method and function names follow the following logic (overriding the Google Python Style Guide):
| Type | Public | Internal |
|---|---|---|
| Functions | CapWords() | _CapWords() (protected) and __CapWords() (private) |
Pylint is used to enforce best practices to keep the source code more readable. These are:
- Limit the maximum number of arguments for function or method to 10
Other things to keep in mind when using Pylint:
- The canonical pylint configuration is generated by l2tdevtools.
- Use textual pylint overrides e.g. "# pylint: disable=no-self-argument" instead of "# pylint: disable=E0213". For a list of overrides see: https://docs.pylint.org/features.html
- In addition to the Google Python Style Guide sort keyword arguments alphabetically by name.
- Call keyword argument with their keyword prefix, not as positional arguments. For example:
def SomeMethod(self, alternate=False, secondary=True):
pass
# No:
SomeMethod(True, False)
# Yes:
SomeMethod(secondary=False)- Quote strings as " (one double quote) or """ (three double quotes). Use ' (one single quote) if there are double quotes in the string.
- Use the f-string notation, instead of the format() function or %-style of formatting strings.
- Use parameter format specifiers with typing e.g. '{text:s}' instead of '{text}'.
- Limit complex statements between the curly brackets. Assign the result of the statement to a local variable before the f-string().
- Only use format() if f-string would make the code unecessary complex.
Tip: use the Python formatting tool black to help ensure strings are quoted appropriately
- When catching exceptions use "as exception:" not some alternative form like "as error:", "as details:" or "as e:"
- Raise exceptions like this:
raise MyException('Error message')orraise MyException. - Although Python allows for
try ... except ... elsewe prefer not to use it. - Make exception messages as useful and descriptive and possible. For example, if an argument is out of an acceptable range, print the invalid value to speed-up debugging.
Per PEP8: "Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable)."
- Use
return Noneinstead ofreturnwhen your function or method is expected to return a value. - Do not use
return Nonein generators. - Use
returnin a function or method that does not return a value.
- Use English, and avoid abbreviations. Use "for example" or "such as" instead of Latin abbreviations like "e.g.".
- Acronyms and initialisms should be preserved, for example HTMLParser and not HtmlParser.
- We use "Google Style" docstrings.
- For examples, see this page as well as the notes below.
Example:
def AddAnalysisReport(self, analysis_report, storage_writer=None):
"""Adds an analysis report.
Args:
analysis_report (AnalysisReport): a report.
storage_writer (Optional[StorageWriter]): the storage writer must be open,
and must not be closed. If no storage_writer is provided, a new writer
will be created.
"""Make sure your arguments descriptions include:
- The argument(s) type(s);
- In case of standard types a description of their format. Note that we use the Python 3 standard types;
- Description of the meaning of the argument. In other words how the argument is used by the function (or method). If the description exceeds the line limit, indent the next line with 4 spaces.
The meaning can be left out if the function has only a couple arguments and how the arguments are used is obvious from the description as in the example of AddAnalysisReport.
A few other tips:
If a function deals with a compound type (list, dict), document it like so:
Args:
constraints (dict[str, Filter]): constraint name mapped to the filter that implements the constraint.
Returns:
list[BaseParser]: all relevant parsers.If you need to specify multiple types, use a pipe to separate them. For example:
Args:
path (str|Path): path to tag file.Python simulates multiple arguments being returned by implicitly returning a tuple. Document like so:
...
Returns:
tuple: containing:
str: parser name
BaseParser: next parser parser
""""
return name, parserArguments like cls, self, *args, **kwargs should not be explicitly named in the Args: section.
def CopyToIsoFormat(cls, timestamp, timezone=pytz.UTC, raise_error=False):
"""Copies the timestamp to an ISO 8601 formatted string.
Args:
timestamp (int): number of micro seconds since January 1, 1970, 00:00:00 UTC.
timezone (Optional[pytz.timezone]): the result string will be expressed in this timezone.
raise_error (Optional[bool]): False if OverflowError should be caught when timestamp is out of bounds.
Returns:
str: ISO 8601 formatted date and time.
"""In addition to the Google Python Style Guide sort class attribute alphabetically by name.
class SampleClass:
"""Summary of class here.
Attributes:
eggs (int): number of eggs we have laid.
likes_spam (bool): whether we like SPAM or not.
"""In addition to the Google Python Style Guide sort instance attribute alphabetically by name inside the constructor (__init__).
class SampleClass:
"""Summary of class here."""
def __init__(self):
"""Summary of method here."""
super().__init__()
self._protected_attribute = None
self.another_public_attribute = None
self.public_attribute = None- Avoid the use of global variables.
- Use class methods in preference to static methods
- Produce an extraction warning (
ProduceExtractionWarning) if a Plaso parser or parser plugin encounters a data format or encoding issue. - Use
decode(errors="backslashreplace")instead ofdecode(errors="ignore")ordecode(errors="replace")
Note that traceability of event data attributes is important, therefore avoid the use of setattr() on event data attributes.
Data type:
- event data attribute containers (objects) must define an unique data_type e.g. "windows:evtx:record". This data type is also used by the timeline and formatters.
- Guidance for the appropriate data type naming:
- if the event data is specific to a platform (e.g. Android or Mac OS) or application (e.g. Chrome or Firefox) use a platform/application prefix e.g. "android:" or "chrome:"
- for events originating from the Windows Registry use the prefix "windows:registry:"
Attribute naming:
- do not use reserved field names, with the exception of "filename", "hostname". "inode" and "username". These include: "date", "datetime", "display_name", "host", "macb", "message", "message_short", "parser", "source", "source_long", "source_short", "sourcetype", "tag", "time", "timestamp", "timestamp_desc", "timezone", "type", "user", "values", "yara_match", "zone".
- do not use "corrupted" or "recovered" instead use Plaso built in functionality to handle these states
- use "description" instead of "desc" or equivalent
- use "filename" instead of "file", "file_name" or equivalent
- use "hostname" instead of "computer_name", "host", "host_name" or equivalent
- use "message_body" instead of "body", "log_line", "message" or equivalent
- use "username" instead of "user", "user_name" or equivalent
Attribute usage:
- an event data attribute value should be of type
bool,int,str,list[str]ordfdatetime.DateTimeValues(or subclass) - if an event data attribute value is empty use None instead of an empty string or equivalent
- use type
boolfor boolean values stored as integers - do not store large binary data (BLOBS) or original log lines, just for context, this can significantly negatively impact performance
- do not use dictionaries as event data attribute value, this is not supported by event filter or OpenSearch output moudle
- do not unecessarily expand values to strings, use a formatter (
plaso/data/formatters/*.yaml) if a value always expands to the same string
- In QUERIES no need to use
ORDER BY, let Plaso handle the sorting. - In QUERIES no need to use formatting functions, let Plaso handle the formatting.
- Use
self.assertEqualinstead ofself.assertEquals, same applies toself.assertNotEquals - Use
self.assertIsNone(variable)instead ofself.assertEqual(variable, None), same applies toself.assertNotEqual
- Only use mock when really necessary
- Do not mix performance (bench or benchmark) tests with unit (functional or behavioral) tests
- When writing tests that involve checking command line output, be aware that Plaso uses argparse which can output terminal colors for Python 3.14 and later. Use
os.environ["NO_COLOR"] = "1"or equivalent to disable terminal colors in tests.
- First make sure the test data has a Plaso compatible license. If the test data was not authored by you (as the contributor), make sure you have permission to use it and mention its orginal source in ACKNOWLEDGEMENTS. Do not include test data that cannot be redistributed.
- Guidance for the most appropriate location of test files in the test_data directory:
- with the exception of generic formats like plist and sqlite use the data format specific sub directory if there is one
- if the test data is specific to a platform (e.g. Android or Mac OS) or application (e.g. Chrome or Firefox) use the platform/application specific sub directory
- otherwise make a data format specific sub directory under "test_data", e.g. "test_data/utmp"
Always use the latest version of black. This is what will be run by the CI tests.
python -m tox -e blackNote docformatter can make formatting changes that black not agrees with. Hence it is recommended to run black consecutively.
python -m tox -e docformatter,blackpython -m tox -e pylintpython -m tox -e yamllint