code: def sort_toctree_by_weight(app, doctree, *args):
      def weight(doc):
          return int(app.env.metadata[doc].get("weight", 0))
  
      for node in doctree.traverse(toctreenode):
          node["entries"].sort(key=lambda entry: weight(entry[1]))
          node["includefiles"].sort(key=weight)
  
imports: import re
  import sys
  from docutils import nodes
  from sphinx.addnodes import toctree
label_desc: Use image node_id 2 for calling a global function with example usage: sort_toctree_by_weight(app, doctree) and returns: int