Source code for cgl.core.notes
import json
import os
from datetime import datetime, date
from cgl.core.path.object import PathObject
[docs]
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError("Type %s not serializable" % type(obj))
# The Notes class is a basic template for creating notes.
[docs]
class Notes(object):
def __init__(self, path_object: PathObject) -> None:
self.path_object: PathObject = path_object
if self.path_object:
self.file_path = self.path_object.get_path()
self.data_path = self.file_path.replace(
os.path.basename(self.file_path),
"." + os.path.basename(self.file_path) + ".njson",
)
if os.path.isfile(self.data_path):
self.load()
else:
self.notes = []
[docs]
def load(self):
with open(self.data_path, "r") as f:
self.notes = json.load(f)
[docs]
def save(self):
with open(self.data_path, "w") as f:
json.dump(self.notes, f, default=json_serial)
print("saving notes to {}".format(self.data_path))
[docs]
def addNote(self, originator, note):
"""
The function adds a note to a list of notes, including the originator, note content, and date.
Args:
originator: The originator parameter represents the user or entity who is adding the note. It
could be a username, user ID, or any other identifier that helps identify the originator of the
note.
note: The "note" parameter is the content of the note that you want to add. It can be a string
or any other data type that represents the content of the note.
"""
self.notes.append(
{"user": originator, "note": note, "date": datetime.now().ctime()}
)
self.save()
[docs]
@staticmethod
def create_from_path_object(path: PathObject):
if isinstance(path, PathObject):
path = PathObject().from_path_string(path)
return Notes(path)
[docs]
@staticmethod
def create_from_path_string(path: str):
if isinstance(path, str):
return Notes(PathObject().from_path_string(path))
if __name__ == "__main__":
# Create a temporary file for testing
temp_file = "temp_file.txt"
with open(temp_file, "w") as f:
f.write("This is a temporary file.")
# Create a PathObject for the temporary file
path_obj = PathObject().from_path_string(temp_file)
path_obj = PathObject.from_path_string(
r"/Users/guillermomolina/Documents/WORK_alchemy/prod/premise/source/Dev/assets/char/jack/mdl/default/guillermo.m/003.001/high"
)
# Create a Notes object from the PathObject
notes = Notes(path_obj)
# Add a note to the Notes object
notes.addNote("User1", "This is a test note.")
# Save the Notes object
notes.save()
# Load the Notes object from the file
notes.load()
# Print the notes
for note in notes.notes:
print(note)
# Remove the temporary file
os.remove(temp_file)