Skip to content

Commit 7ab68d0

Browse files
committed
Refactor Git export functionality: add new utilities for repository management and enhance initial commit generation workflow
1 parent 9875e49 commit 7ab68d0

5 files changed

Lines changed: 338 additions & 73 deletions

File tree

exporters/git/__init__.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,21 @@
11
"""Git export functionality for SFS documents."""
22

3-
from .git_utils import ensure_git_branch_for_commits, restore_original_branch, remove_all_commits_on_branch
3+
from .git_utils import (
4+
ensure_git_branch_for_commits,
5+
restore_original_branch,
6+
remove_all_commits_on_branch,
7+
get_target_repository,
8+
configure_git_remote,
9+
push_to_target_repository
10+
)
11+
from .generate_init_commit_for_doc import generate_init_commit_for_document
412

5-
__all__ = ['ensure_git_branch_for_commits', 'restore_original_branch', 'remove_all_commits_on_branch']
13+
__all__ = [
14+
'ensure_git_branch_for_commits',
15+
'restore_original_branch',
16+
'remove_all_commits_on_branch',
17+
'get_target_repository',
18+
'configure_git_remote',
19+
'push_to_target_repository',
20+
'generate_init_commit_for_document'
21+
]

exporters/git/generate_commits.py

Lines changed: 34 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from temporal.upcoming_changes import identify_upcoming_changes
1616
from temporal.apply_temporal import apply_temporal
1717
from exporters.git.git_utils import GIT_TIMEOUT
18-
from exporters.git import ensure_git_branch_for_commits, restore_original_branch
18+
from exporters.git import push_to_target_repository
1919
from util.datetime_utils import format_datetime_for_git
2020
from util.yaml_utils import extract_frontmatter_property
2121
from util.file_utils import save_to_disk
@@ -27,7 +27,6 @@ def create_init_git_commit(
2727
beteckning: str,
2828
rubrik: str,
2929
utfardad_datum: str,
30-
git_branch: str = None,
3130
predocs: Optional[str] = None,
3231
verbose: bool = False
3332
) -> bool:
@@ -39,7 +38,6 @@ def create_init_git_commit(
3938
beteckning: Document ID
4039
rubrik: Document title
4140
utfardad_datum: Issue date
42-
git_branch: Branch name for commits
4341
predocs: Preparatory works (förarbeten) if available
4442
verbose: Enable verbose output
4543
@@ -48,15 +46,6 @@ def create_init_git_commit(
4846
"""
4947
import subprocess
5048

51-
# Ensure commits are made in a different branch
52-
original_branch, commit_branch = ensure_git_branch_for_commits(git_branch, remove_all_commits_first=True, verbose=verbose)
53-
54-
# Only proceed with git commits if branch creation was successful
55-
if original_branch is None or commit_branch is None:
56-
print(f"Hoppar över Git-commits för {beteckning} på grund av branch-problem")
57-
save_to_disk(output_file, markdown_content)
58-
return False
59-
6049
# Prepare commit message
6150
commit_message = rubrik if rubrik else f"SFS {beteckning}"
6251

@@ -98,15 +87,11 @@ def create_init_git_commit(
9887
print(f"Git stderr: {e.stderr.decode('utf-8', errors='replace')}")
9988
# Write the file anyway, without git commits
10089
save_to_disk(output_file, markdown_content)
101-
# Restore original branch on error
102-
restore_original_branch(original_branch)
10390
return False
10491
except FileNotFoundError:
10592
print("Varning: Git hittades inte. Hoppar över Git-commits.")
10693
# Write the file anyway, without git commits
10794
save_to_disk(output_file, markdown_content)
108-
# Restore original branch on error
109-
restore_original_branch(original_branch)
11095
return False
11196

11297

@@ -270,7 +255,8 @@ def generate_commits(
270255
doc_name: Optional[str] = None,
271256
from_date: Optional[str] = None,
272257
to_date: Optional[str] = None,
273-
dry_run: bool = False
258+
dry_run: bool = False,
259+
push_to_remote: bool = False
274260
) -> None:
275261
"""
276262
Generate Git commits for temporal changes in a markdown file.
@@ -284,6 +270,7 @@ def generate_commits(
284270
from_date: Start date (inclusive) in YYYY-MM-DD format. If None, no lower bound.
285271
to_date: End date (inclusive) in YYYY-MM-DD format. If None, no upper bound.
286272
dry_run: If True, show what would be committed without making actual commits
273+
push_to_remote: If True, push commits to the target repository configured via environment variables
287274
288275
Raises:
289276
ValueError: If date format is invalid
@@ -441,6 +428,25 @@ def generate_commits(
441428
if hasattr(e, 'stderr') and e.stderr:
442429
print(f"Git stderr: {e.stderr.decode('utf-8', errors='replace')}")
443430

431+
# Push to target repository if requested
432+
if push_to_remote and not dry_run:
433+
try:
434+
# Get current branch name for pushing
435+
result = subprocess.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
436+
capture_output=True, text=True, check=True, timeout=GIT_TIMEOUT)
437+
current_branch = result.stdout.strip()
438+
439+
print(f"Pushar commits till target repository...")
440+
if push_to_target_repository(current_branch, verbose=True):
441+
print(f"Lyckades pusha branch '{current_branch}' till target repository")
442+
else:
443+
print("Misslyckades med att pusha till target repository")
444+
445+
except subprocess.CalledProcessError as e:
446+
print(f"Fel vid push till target repository: {e}")
447+
if hasattr(e, 'stderr') and e.stderr:
448+
print(f"Git stderr: {e.stderr.decode('utf-8', errors='replace')}")
449+
444450
# Restore original content after all commits
445451
try:
446452
save_to_disk(markdown_file, original_content)
@@ -452,7 +458,8 @@ def generate_commits_for_directory(
452458
directory: Path,
453459
from_date: Optional[str] = None,
454460
to_date: Optional[str] = None,
455-
dry_run: bool = False
461+
dry_run: bool = False,
462+
push_to_remote: bool = False
456463
) -> None:
457464
"""
458465
Generate Git commits for all markdown files in a directory.
@@ -462,6 +469,7 @@ def generate_commits_for_directory(
462469
from_date: Start date (inclusive) in YYYY-MM-DD format. If None, no lower bound.
463470
to_date: End date (inclusive) in YYYY-MM-DD format. If None, no upper bound.
464471
dry_run: If True, show what would be committed without making actual commits
472+
push_to_remote: If True, push commits to the target repository configured via environment variables
465473
"""
466474
if not directory.exists():
467475
print(f"Fel: Katalogen {directory} finns inte")
@@ -484,7 +492,7 @@ def generate_commits_for_directory(
484492
print(f"\nBearbetar {md_file.name}...")
485493

486494
try:
487-
generate_commits(md_file, None, from_date, to_date, dry_run)
495+
generate_commits(md_file, None, from_date, to_date, dry_run, push_to_remote)
488496
except Exception as e:
489497
print(f"Fel vid bearbetning av {md_file}: {e}")
490498

@@ -512,14 +520,19 @@ def generate_commits_for_directory(
512520
action='store_true',
513521
help='Visa planerade commits utan att utföra dem'
514522
)
523+
parser.add_argument(
524+
'--push',
525+
action='store_true',
526+
help='Pusha commits till target repository (konfigurerat via GIT_TARGET_REPO och GIT_GITHUB_PAT)'
527+
)
515528

516529
args = parser.parse_args()
517530

518531
path = Path(args.path)
519532

520533
if path.is_file():
521-
generate_commits(path, None, args.from_date, args.to_date, args.dry_run)
534+
generate_commits(path, None, args.from_date, args.to_date, args.dry_run, args.push)
522535
elif path.is_dir():
523-
generate_commits_for_directory(path, args.from_date, args.to_date, args.dry_run)
536+
generate_commits_for_directory(path, args.from_date, args.to_date, args.dry_run, args.push)
524537
else:
525538
print(f"Fel: {path} finns inte")
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Module for generating initial Git commits for SFS documents.
4+
5+
This module handles the complete git workflow for creating initial commits
6+
for SFS documents, including branch management and cleanup.
7+
"""
8+
9+
from pathlib import Path
10+
from typing import Optional
11+
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 util.file_utils import save_to_disk
15+
from formatters.format_sfs_text import clean_selex_tags
16+
from util.datetime_utils import format_datetime
17+
18+
19+
def generate_init_commit_for_document(
20+
data: dict,
21+
output_file: Path,
22+
markdown_content: str,
23+
git_branch: str,
24+
preserve_section_tags: bool = False,
25+
verbose: bool = False
26+
) -> str:
27+
"""
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+
36+
Args:
37+
data: JSON data containing document information
38+
output_file: Path to the output markdown file
39+
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
42+
verbose: Enable verbose output
43+
44+
Returns:
45+
str: The final markdown content (cleaned if preserve_section_tags is False)
46+
"""
47+
# 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+
)
58+
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}")
62+
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}")
83+
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}")
87+
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+
97+
return final_content

0 commit comments

Comments
 (0)