"Example of Python file we would like to index"classMyType:my_member=Truedefmy_method(self):returnself.my_member
Database Manipulation
First we are going to create a SourcetrailDB database. It could be done using
either open or create, depending
on if you want to open an already existing db or create one. In this tutorial we will create a new one or clear the old
one with the same name using the following code.
fromnumbatimportSourcetrailDBfrompathlibimportPathdb=SourcetrailDB.open(Path('my_database'),clear=True)# do some stuffdb.commit()db.close()
It will create two files: a Sourcetrail DB file (.srctrldb) and project file (.srctrlprj). You can open the second
one with your local Sourcetrail to explore your data.
Add Symbols
We could add a lot of different symbols as described in
the full API reference but in anycase, they all have the
same signature:
When we open the current database with Sourcetrail after running this script, we obtain the following view:
Relationships
It is possible to add links between the different symbols after they have been created with the
commands record_ref_XX. These relationships could be
of several types. Here, in file.py, we can see that my_method is
using the field my_member, so we could add an USAGE relation.
fromnumbatimportSourcetrailDBfrompathlibimportPathdb=SourcetrailDB.open(Path('my_database'),clear=True)# Record filefile_id=db.record_file(Path('file.py'))db.record_file_language(file_id,'python')# Add symbolsclass_id=db.record_class(prefix="class",name="MyType",postfix="():")field_id=db.record_field(name="my_member",parent_id=class_id)db.record_symbol_location(field_id,file_id,4,4,4,12)meth_id=db.record_method(name="my_method",parent_id=class_id)# Add relationshipsdb.record_ref_usage(meth_id,field_id)db.commit()db.close()
Link Symbols and Source Code
As you have inserted the source code and the symbols, you should create links between them to indicate to Sourcetrail where each symbol is located in the code, and if it is the case, its scope. For that, you could respectively use the record_symbol_location and record_symbol_scope_location methods.