22"""
33Module for generating initial Git commits for SFS documents.
44
5- This module handles the complete git workflow for creating initial commits
6- for SFS documents, including branch management and cleanup .
5+ This module handles creating commits for SFS documents without managing
6+ the overall git workflow (branching, pushing, etc) .
77"""
88
9+ import os
10+ import re
11+ import subprocess
912from pathlib import Path
10- from typing import Optional
1113
12- from exporters .git import ensure_git_branch_for_commits , restore_original_branch
13- from exporters .git .generate_commits import create_init_git_commit
14+ from exporters .git .git_utils import GIT_TIMEOUT
1415from util .file_utils import save_to_disk
1516from formatters .format_sfs_text import clean_selex_tags
16- from util .datetime_utils import format_datetime
17+ from util .datetime_utils import format_datetime , format_datetime_for_git
1718
1819
1920def generate_init_commit_for_document (
2021 data : dict ,
2122 output_file : Path ,
2223 markdown_content : str ,
23- git_branch : str ,
24- preserve_section_tags : bool = False ,
2524 verbose : bool = False
2625) -> str :
2726 """
28- Generate initial git commit for an SFS document with proper branch handling.
29-
30- This function handles the complete git workflow:
31- 1. Creates a separate git branch for commits
32- 2. Creates the initial commit with document metadata
33- 3. Restores the original branch
34- 4. Writes the final file content
35-
27+ Generate initial git commit for an SFS document.
28+
29+ This function handles creating commits for individual documents.
30+ It assumes we're already in a git repository and on the correct branch.
31+
3632 Args:
3733 data: JSON data containing document information
38- output_file: Path to the output markdown file
34+ output_file: Path to the output markdown file (for local reference)
3935 markdown_content: The markdown content to commit and save
40- git_branch: Branch name to use for git commits
41- preserve_section_tags: Whether to preserve <section> tags in final output
4236 verbose: Enable verbose output
43-
37+
4438 Returns:
45- str: The final markdown content (cleaned if preserve_section_tags is False )
39+ str: The final markdown content (cleaned, without selex tags )
4640 """
4741 # Extract document metadata
48- beteckning = data .get ('beteckning' , 'Unknown' )
49- rubrik = data .get ('rubrik' , '' )
50- utfardad_datum = format_datetime (data .get ('fulltext' , {}).get ('utfardadDateTime' ))
51-
52- # Ensure commits are made in a different branch
53- original_branch , commit_branch = ensure_git_branch_for_commits (
54- git_branch ,
55- remove_all_commits_first = True ,
56- verbose = verbose
57- )
42+ beteckning = data .get ('beteckning' )
43+ if not beteckning :
44+ raise ValueError ("Beteckning saknas i dokumentdata" )
5845
59- # Ensure branch creation was successful
60- if original_branch is None or commit_branch is None :
61- raise RuntimeError ( f"Misslyckades att skapa git branch för { beteckning } " )
46+ rubrik = data . get ( 'rubrik' )
47+ if not rubrik :
48+ raise ValueError ( "Rubrik saknas i dokumentdata " )
6249
63- try :
64- # Only create main commit if we have utfardad_datum
65- if utfardad_datum :
66- # Get förarbeten if available
67- register_data = data .get ('register' , {})
68- predocs = register_data .get ('forarbeten' )
69-
70- # Create initial git commit
71- success = create_init_git_commit (
72- output_file = output_file ,
73- markdown_content = markdown_content ,
74- beteckning = beteckning ,
75- rubrik = rubrik ,
76- utfardad_datum = utfardad_datum ,
77- predocs = predocs ,
78- verbose = verbose
79- )
80-
81- if not success :
82- print (f"Git-commit misslyckades för { beteckning } " )
50+ utfardad_datum = format_datetime (data .get ('fulltext' , {}).get ('utfardadDateTime' ))
51+
52+ # Prepare final content for local save (always clean selex tags in git mode)
53+ final_content = clean_selex_tags (markdown_content )
54+
55+ # Save file locally for reference
56+ save_to_disk (output_file , final_content )
57+ print (f"Skapade dokument: { output_file } " )
58+
59+ # Create git commit if we have utfardad_datum
60+ if utfardad_datum :
61+ # Extract year from beteckning for directory structure
62+ year_match = re .search (r'(\d{4}):' , beteckning )
63+ if year_match :
64+ year = year_match .group (1 )
65+ relative_path = Path (year ) / output_file .name
8366 else :
84- # Write file if no utfardad_datum available
85- save_to_disk (output_file , markdown_content )
86- print (f"Skrev fil utan git-commit (inget utfärdandedatum): { output_file } " )
67+ relative_path = Path (output_file .name )
68+
69+ # Create directory structure if needed
70+ target_file = Path .cwd () / relative_path
71+ target_file .parent .mkdir (parents = True , exist_ok = True )
72+
73+ # Write the file (use clean content without selex tags for git)
74+ clean_content = clean_selex_tags (markdown_content )
8775
88- finally :
89- # Always restore original branch after git operations
90- restore_original_branch (original_branch )
91-
92- # Prepare final content for return
93- final_content = markdown_content
94- if not preserve_section_tags :
95- final_content = clean_selex_tags (final_content )
96-
76+ with open (target_file , 'w' , encoding = 'utf-8' ) as f :
77+ f .write (clean_content )
78+
79+ # Stage the file
80+ subprocess .run (['git' , 'add' , str (relative_path )],
81+ check = True , capture_output = True , timeout = GIT_TIMEOUT )
82+
83+ # Prepare commit message
84+ commit_message = rubrik
85+
86+ # Add förarbeten if available
87+ register_data = data .get ('register' , {})
88+ predocs = register_data .get ('forarbeten' )
89+ if predocs :
90+ commit_message += (f"\n \n Har tillkommit i Svensk författningssamling "
91+ f"efter dessa förarbeten: { predocs } " )
92+
93+ # Format date for git
94+ commit_date = format_datetime_for_git (utfardad_datum )
95+
96+ # Create commit with specified date
97+ env = {** os .environ , 'GIT_AUTHOR_DATE' : commit_date , 'GIT_COMMITTER_DATE' : commit_date }
98+ subprocess .run ([
99+ 'git' , 'commit' , '-m' , commit_message
100+ ], check = True , capture_output = True , env = env , timeout = GIT_TIMEOUT )
101+
102+ if verbose :
103+ print (f"Git-commit skapad: '{ commit_message } ' daterad { commit_date } " )
104+
105+ elif not utfardad_datum :
106+ if verbose :
107+ print (f"Hoppade över git-commit (inget utfärdandedatum): { beteckning } " )
108+
97109 return final_content
0 commit comments