@@ -367,12 +367,13 @@ def get_articles_from_category(category_dir, category_slug):
367367 category_slug: The slug of the category
368368
369369 Returns:
370- A list of article dictionaries
370+ A list of article dictionaries, sorted from most to least
371+ recently published (by the `publish_date` frontmatter field).
372+ Articles missing `publish_date` sort to the end.
371373 """
372374 articles = []
373- md_files = sorted (category_dir .glob ("*.md" ))
374375
375- for md_file in md_files :
376+ for md_file in category_dir . glob ( "*.md" ) :
376377 try :
377378 with open (md_file , "r" , encoding = "utf-8" ) as f :
378379 content = f .read ()
@@ -383,30 +384,55 @@ def get_articles_from_category(category_dir, category_slug):
383384 if len (parts ) >= 2 :
384385 try :
385386 frontmatter = yaml .safe_load (parts [1 ])
387+ context = frontmatter .get ("context" , {}) or {}
386388 article_slug = md_file .stem
387389
390+ publish_date = context .get ("publish_date" )
391+ # yaml may parse ISO dates into date/datetime objects;
392+ # accept strings too and normalise.
393+ if isinstance (publish_date , datetime .datetime ):
394+ publish_date = publish_date .date ()
395+ elif isinstance (publish_date , str ):
396+ try :
397+ publish_date = datetime .date .fromisoformat (
398+ publish_date
399+ )
400+ except ValueError :
401+ logger .warning (
402+ f"Invalid publish_date in { md_file } : "
403+ f"{ publish_date !r} "
404+ )
405+ publish_date = None
406+
388407 # Build article metadata
389408 article = {
390- "hero_title" : frontmatter . get ( " context" , {}) .get (
409+ "hero_title" : context .get (
391410 "hero_title" , md_file .stem
392411 ),
393- "description" : frontmatter .get ("context" , {}).get (
394- "description" , ""
395- ),
412+ "description" : context .get ("description" , "" ),
396413 "url" : (
397414 f"/knowledge/{ category_slug } /"
398415 f"{ article_slug } "
399416 ),
400- "tag" : frontmatter .get ("context" , {}).get (
401- "tag" , ""
402- ),
417+ "tag" : context .get ("tag" , "" ),
418+ "publish_date" : publish_date ,
403419 }
404420 articles .append (article )
405421 except yaml .YAMLError :
406422 logger .error (f"YAML parsing error in { md_file } " )
407423 except Exception as e :
408424 logger .error (f"Error reading { md_file } : { e } " )
409425
426+ # Sort most → least recently published. Articles without a publish_date
427+ # fall to the end; ties break alphabetically by hero_title for stability.
428+ articles .sort (
429+ key = lambda a : (
430+ a ["publish_date" ] is None ,
431+ - (a ["publish_date" ].toordinal () if a ["publish_date" ] else 0 ),
432+ a ["hero_title" ].lower (),
433+ )
434+ )
435+
410436 return articles
411437
412438
0 commit comments