-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpipeline.py
More file actions
executable file
·1435 lines (1147 loc) · 48.9 KB
/
pipeline.py
File metadata and controls
executable file
·1435 lines (1147 loc) · 48.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Resume Pipeline - Interactive CLI Manager
A unified command-line interface for managing your resume pipeline.
Provides both interactive menus and command-line flags for automation.
Usage:
python pipeline.py # Interactive mode
python pipeline.py --help # Show all options
python pipeline.py --new-version # Create new version interactively
python pipeline.py --set-version # Select version interactively
python pipeline.py --build # Build current version
python pipeline.py --validate # Validate current version
python pipeline.py --export # Export current version to markdown
python pipeline.py --clean # Clean build artifacts
python pipeline.py --duplicate src # Duplicate a version
python pipeline.py --delete old # Delete a version
python pipeline.py --list # List all versions
python pipeline.py --refresh-library # Regenerate CV library JSON
python pipeline.py --status # Show pipeline status
"""
import sys
import argparse
from pathlib import Path
from typing import Optional, List
import shutil
import subprocess
import json
import re
import os
import datetime
# Add scripts directory to path
SCRIPTS_DIR = Path(__file__).parent / 'scripts'
sys.path.insert(0, str(SCRIPTS_DIR))
from cv_parser import CVParser # noqa: E402
from generate_tasks import generate_tasks_json # noqa: E402
from cv_utils import Colors # noqa: E402
# Helper functions to work with existing scripts
def get_available_versions() -> List[str]:
"""Get list of available versions from _content/."""
content_path = Path.cwd() / '_content'
if not content_path.exists():
return []
versions = sorted([
d.name for d in content_path.iterdir()
if d.is_dir() and not d.name.startswith('_')
])
return versions
def get_current_version() -> str:
"""Get the current version from cv-version.tex."""
version_file = Path.cwd() / 'cv-version.tex'
if not version_file.exists():
return 'default'
try:
with open(version_file, 'r', encoding='utf-8') as f:
content = f.read()
# Extract version from \newcommand{\OutputVersion}{version_name}
match = re.search(r'\\newcommand\{\\OutputVersion\}\{([^}]+)\}', content)
if match:
return match.group(1)
except Exception:
pass
return 'default'
def get_version_status(version: str) -> str:
"""Get status indicator for a version."""
content_path = Path.cwd() / '_content'
version_dir = content_path / version
if not version_dir.exists():
return '[Not Found]'
has_tagline = (version_dir / "tagline.tex").exists()
has_experience = (version_dir / "experience.tex").exists()
has_cover_letter = (version_dir / "cover_letter.tex").exists()
if has_tagline and has_experience and has_cover_letter:
return '[Complete]'
elif has_tagline and has_experience:
return '[Resume Ready]'
elif has_tagline or has_experience or has_cover_letter:
return '[Partial]'
else:
return '[Empty]'
def update_version(version: str) -> None:
"""Update the version in cv-version.tex."""
version_file = Path.cwd() / 'cv-version.tex'
if not version_file.exists():
# If file doesn't exist, create with minimal content
content = f"\\newcommand{{\\OutputVersion}}{{{version}}}\n"
version_file.write_text(content, encoding='utf-8')
return
# Read all lines and replace only the \newcommand line
lines = version_file.read_text(encoding='utf-8').splitlines()
new_lines = []
found = False
for line in lines:
if line.strip().startswith('\\newcommand{\\OutputVersion}'):
new_lines.append(f"\\newcommand{{\\OutputVersion}}{{{version}}}")
found = True
else:
new_lines.append(line)
if not found:
# If the command was not found, append it at the end
new_lines.append(f"\\newcommand{{\\OutputVersion}}{{{version}}}")
version_file.write_text('\n'.join(new_lines) + '\n', encoding='utf-8')
def clear_screen():
"""Clear the terminal screen."""
os.system('cls' if os.name == 'nt' else 'clear')
def print_header(text: str):
"""Print a styled header."""
print(f"\n{Colors.BOLD}{Colors.CYAN}{'=' * 60}{Colors.ENDC}")
print(f"{Colors.BOLD}{Colors.CYAN}{text.center(60)}{Colors.ENDC}")
print(f"{Colors.BOLD}{Colors.CYAN}{'=' * 60}{Colors.ENDC}\n")
def print_success(text: str):
"""Print success message."""
print(f"{Colors.GREEN}✓ {text}{Colors.ENDC}")
def print_error(text: str):
"""Print error message."""
print(f"{Colors.RED}✗ {text}{Colors.ENDC}")
def print_info(text: str):
"""Print info message."""
print(f"{Colors.BLUE}ℹ {text}{Colors.ENDC}")
def print_warning(text: str):
"""Print warning message."""
print(f"{Colors.YELLOW}⚠ {text}{Colors.ENDC}")
def create_new_version(version_name: Optional[str] = None) -> bool:
"""Create a new resume version from template.
Args:
version_name: Optional name for the version. If None, prompts user.
Returns:
True if successful, False otherwise.
"""
print_header("Create New Resume Version")
base_path = Path.cwd()
content_dir = base_path / '_content'
template_dir = content_dir / '_template'
if not template_dir.exists():
print_error("Template directory not found at _content/_template/")
return False
# Get version name
if version_name is None:
print_info("Enter a name for the new version (e.g., 'acme_corp', 'senior_engineer')")
print_info("Use lowercase with underscores, no spaces")
version_name = input(f"{Colors.BOLD}Version name: {Colors.ENDC}").strip()
if not version_name:
print_error("Version name cannot be empty")
return False
# Normalize version name
normalized = re.sub(r'[^a-zA-Z0-9_-]', '', version_name.replace(' ', '_').lower())
if version_name != normalized:
print_warning(f"Version name '{version_name}' is not in the recommended format.")
print_info(f"Suggested: {Colors.CYAN}{normalized}{Colors.ENDC}")
action = input(f"Use suggested name? (Y/edit/cancel): {Colors.ENDC}").strip().lower()
if action == 'y' or action == 'yes' or action == '':
version_name = normalized
elif action == 'edit':
version_name = input(f"{Colors.BOLD}Edit version name: {Colors.ENDC}").strip()
if not version_name:
print_error("Version name cannot be empty")
return False
version_name = re.sub(r'[^a-zA-Z0-9_-]', '', version_name.replace(' ', '_').lower())
else:
print_info("Cancelled")
return False
# Validate version name
if not version_name.replace('_', '').replace('-', '').isalnum():
print_error("Version name must contain only letters, numbers, underscores, and hyphens")
return False
# Prepend today's date to the folder name unless already present
date_prefix_pattern = r'^\d{4}-\d{2}-\d{2}_'
if re.match(date_prefix_pattern, version_name):
final_name = version_name
else:
today = datetime.date.today().isoformat()
final_name = f"{today}_{version_name}"
new_version_dir = content_dir / final_name
# Check if version already exists
if new_version_dir.exists():
print_error(f"Version '{final_name}' already exists!")
return False
# Show preview
print(f"\n{Colors.BOLD}Preview:{Colors.ENDC}")
print(f" Name: {Colors.CYAN}{final_name}{Colors.ENDC}")
print(f" Path: {Colors.CYAN}{new_version_dir.relative_to(base_path)}{Colors.ENDC}")
print(f"\n{Colors.BOLD}Files to be created:{Colors.ENDC}")
template_files = sorted([f.name for f in template_dir.glob('*.tex')])
for file in template_files:
print(f" - {file}")
# Confirm
confirm = input(f"\n{Colors.BOLD}Create this version? (y/N): {Colors.ENDC}").strip().lower()
if confirm != 'y':
print_info("Cancelled")
return False
# Copy template, skipping .gitignore
try:
new_version_dir.mkdir(parents=True, exist_ok=False)
for item in template_dir.iterdir():
if item.name == '.gitignore':
continue
if item.is_file():
shutil.copy2(item, new_version_dir / item.name)
elif item.is_dir():
shutil.copytree(item, new_version_dir / item.name)
print_success(f"Created new version: {final_name}")
# Ask if user wants to switch to it
switch = input(f"\n{Colors.BOLD}Switch to this version now? (Y/n): {Colors.ENDC}").strip().lower()
if switch != 'n':
update_version(final_name)
print_success(f"Switched to version: {final_name}")
# Suggest next steps
print(f"\n{Colors.BOLD}Next steps:{Colors.ENDC}")
print(f" 1. Edit files in {Colors.CYAN}_content/{final_name}/{Colors.ENDC}")
print(" 2. Customize the content for your specific use case")
print(f" 3. Run {Colors.CYAN}python pipeline.py --build{Colors.ENDC} to generate PDF")
return True
except Exception as e:
print_error(f"Failed to create version: {e}")
return False
def select_version_interactive() -> bool:
"""Interactive version selection with status indicators.
Returns:
True if version was changed, False otherwise.
"""
clear_screen()
print(f"\n {Colors.DIM}Resume Pipeline{Colors.ENDC} {Colors.CYAN}›{Colors.ENDC} {Colors.BOLD}Switch Version{Colors.ENDC}\n") # noqa e501
versions = get_available_versions()
current = get_current_version()
if not versions:
print_error("No versions found in _content/")
return False
print(f" {Colors.DIM}Current:{Colors.ENDC} {Colors.CYAN}{Colors.BOLD}{current}{Colors.ENDC}")
print(f" {Colors.DIM}Legend: {Colors.GREEN}●{Colors.ENDC} Complete {Colors.CYAN}●{Colors.ENDC} Resume Ready {Colors.YELLOW}●{Colors.ENDC} Partial{Colors.ENDC}\n") # noqa e501
# Display versions with status
for i, version in enumerate(versions, 1):
status = get_version_status(version)
current_marker = f" {Colors.DIM}(current){Colors.ENDC}" if version == current else ""
# Color-code status
if status == '[Complete]':
status_colored = f"{Colors.GREEN}●{Colors.ENDC}"
elif status == '[Resume Ready]':
status_colored = f"{Colors.CYAN}●{Colors.ENDC}"
else:
status_colored = f"{Colors.YELLOW}●{Colors.ENDC}"
# Truncate long names
display_name = version[:45] + "..." if len(version) > 48 else version
print(f" {Colors.BOLD}{i:2}{Colors.ENDC} {status_colored} {display_name}{current_marker}")
print(f"\n {Colors.DIM} 0 › Cancel{Colors.ENDC}")
# Get selection
try:
choice = input(f"\n{Colors.BOLD}›{Colors.ENDC} ").strip()
if choice == '0' or choice == '':
print_info("Cancelled")
return False
choice_num = int(choice)
if 1 <= choice_num <= len(versions):
selected = versions[choice_num - 1]
if selected == current:
print_info(f"Already using version: {selected}")
return False
update_version(selected)
print_success(f"Switched to version: {selected}")
return True
else:
print_error("Invalid selection")
return False
except ValueError:
print_error("Invalid input")
return False
def list_versions() -> None:
"""List all available versions with their status."""
print_header("Available Resume Versions")
versions = get_available_versions()
current = get_current_version()
if not versions:
print_error("No versions found in _content/")
return
print(f"Current version: {Colors.CYAN}{Colors.BOLD}{current}{Colors.ENDC}\n")
for version in versions:
status = get_version_status(version)
current_marker = " ← current" if version == current else ""
# Color-code status
if status == '[Complete]':
status_colored = f"{Colors.GREEN}{status}{Colors.ENDC}"
elif status == '[Resume Ready]':
status_colored = f"{Colors.CYAN}{status}{Colors.ENDC}"
else:
status_colored = f"{Colors.YELLOW}{status}{Colors.ENDC}"
print(f" {Colors.BOLD}{version}{Colors.ENDC} {status_colored}{current_marker}")
def build_resume(version: Optional[str] = None, combine: bool = False) -> bool:
"""Build resume PDF(s) for a version.
Args:
version: Version to build. If None, uses current version.
combine: If True, attempt to combine cover letter and resume into a
single PDF (cover first) using a small LaTeX wrapper and
an available TeX engine. This avoids adding Python-only
dependencies.
Returns:
True if successful, False otherwise.
"""
if version is None:
version = get_current_version()
print_header(f"Building Resume & Cover Letter: {version}")
try:
# Run build script for both resume and cover letter
result = subprocess.run(
[sys.executable, str(SCRIPTS_DIR / 'build.py')],
capture_output=True,
text=True
)
print(result.stdout)
# Check for cover letter section
content_dir = Path.cwd() / '_content' / version
cover_letter_path = content_dir / 'cover_letter.tex'
if not cover_letter_path.exists():
print_warning("No cover letter section found for this version. Skipping cover letter build.")
if result.returncode == 0:
print_success(f"Resume and cover letter build complete for version: {version}")
# If requested, attempt to combine the generated PDFs.
if combine:
try:
output_dir = Path.cwd() / '_output' / version
# Attempt to locate cover and resume PDFs by common naming
cover_pdf = None
resume_pdf = None
# Common produced names by scripts/build.py: "<Full Name> Cover Letter.pdf"
# and "<Full Name> Resume.pdf" - match by suffix
if output_dir.exists():
for p in output_dir.glob('*.pdf'):
name = p.name.lower()
if 'cover' in name and 'letter' in name:
cover_pdf = p
if 'resume' in name:
resume_pdf = p
# Fallbacks
if cover_pdf is None:
possible = output_dir / 'cover_letter.pdf'
if possible.exists():
cover_pdf = possible
if resume_pdf is None:
possible = output_dir / 'resume.pdf'
if possible.exists():
resume_pdf = possible
if not output_dir.exists() or cover_pdf is None or resume_pdf is None:
print_warning('Could not find both cover letter and resume PDFs to combine. Skipping combine.')
else:
dest_name = f"{version}-combined.pdf"
dest = output_dir / dest_name
combined = combine_pdfs_via_latex(output_dir, cover_pdf, resume_pdf, dest)
if combined:
print_success(f"Combined PDF created: {combined.relative_to(Path.cwd())}")
else:
print_warning('Combine step did not produce a combined PDF')
except Exception as e:
print_warning(f'Combine failed: {e}')
return True
else:
print_error("Build failed")
if result.stderr:
print(result.stderr)
return False
except Exception as e:
print_error(f"Build error: {e}")
return False
def refresh_library() -> bool:
"""Regenerate the CV library JSON files.
Returns:
True if successful, False otherwise.
"""
print_header("Refresh CV Library")
print_info("Parsing all CV versions...")
try:
parser = CVParser()
print_info("Parsing CV files...")
parser.parse_all_cvs()
print_info("Merging jobs by company/year...")
parser.merge_jobs()
print_info("Exporting to JSON...")
parser.export_to_json()
print_success("CV library refreshed successfully!")
return True
except Exception as e:
print_error(f"Failed to refresh library: {e}")
return False
def combine_pdfs_via_latex(output_dir: Path, cover_pdf: Path, resume_pdf: Path, dest: Path) -> Optional[Path]:
"""Combine two PDFs (cover then resume) by generating a small LaTeX wrapper
that uses the `pdfpages` package. This avoids adding Python PDF libraries.
Returns the destination Path on success, or None on failure.
"""
# Ensure output dir exists
output_dir = Path(output_dir)
if not output_dir.exists():
print_warning(f"Output directory does not exist: {output_dir}")
return None
if not cover_pdf.exists() or not resume_pdf.exists():
print_warning("Cover or resume PDF missing for combine")
return None
tex_name = 'combine_cover_resume.tex'
tex_path = output_dir / tex_name
tex_contents = rf"""\documentclass{{article}}
\usepackage{{pdfpages}}
\pagestyle{{empty}}
\begin{{document}}
\includepdf[pages=-]{{{cover_pdf.name}}}
\includepdf[pages=-]{{{resume_pdf.name}}}
\end{{document}}
"""
tex_path.write_text(tex_contents, encoding='utf-8')
# Run tectonic from project root, mirroring scripts/build.py behavior
project_root = Path.cwd()
# Require tectonic specifically for combining to keep behavior consistent
if not shutil.which('tectonic'):
print_warning('Tectonic not found; combine requires tectonic to be installed.')
return None
try:
cmd = [
'tectonic',
'--keep-logs',
'--keep-intermediates',
'--outdir', str(output_dir),
'-Z', f'search-path={project_root}',
'-Z', f'search-path={output_dir}',
str(tex_path.resolve())
]
subprocess.run(cmd, check=True, capture_output=True, text=True, cwd=str(project_root))
except subprocess.CalledProcessError as e:
print_warning(f"LaTeX combine failed: {e.stderr if hasattr(e, 'stderr') else e}")
return None
built_pdf = output_dir / (tex_path.stem + '.pdf')
if built_pdf.exists():
# Move to destination atomically when possible
tmp = dest.with_suffix(dest.suffix + '.tmp')
try:
if tmp.exists():
tmp.unlink()
shutil.move(str(built_pdf), str(tmp))
if dest.exists():
dest.unlink()
tmp.replace(dest)
except Exception:
# Fallback copy
shutil.copy2(str(built_pdf), str(dest))
# Cleanup intermediate files
for ext in ['.aux', '.log', '.out', '.fls', '.toc', '.fdb_latexmk']:
p = output_dir / (tex_path.stem + ext)
if p.exists():
try:
p.unlink()
except Exception:
pass
# Attempt latexmk cleanup if available
if shutil.which('latexmk'):
try:
subprocess.run(['latexmk', '-c', tex_path.name], check=False, capture_output=True, text=True, cwd=str(project_root))
except Exception:
pass
try:
tex_path.unlink()
except Exception:
pass
return dest
return None
def combine_current_version(version: Optional[str] = None) -> bool:
"""Combine the cover letter and resume PDFs for the given version (or current).
Uses `combine_pdfs_via_latex` (tectonic-only) and reports success/failure.
"""
if version is None:
version = get_current_version()
print_header(f"Combine Cover Letter + Resume: {version}")
output_dir = Path.cwd() / '_output' / version
if not output_dir.exists():
print_error(f"Output directory not found for version: {version}")
return False
cover_pdf = None
resume_pdf = None
for p in output_dir.glob('*.pdf'):
name = p.name.lower()
if 'cover' in name and 'letter' in name:
cover_pdf = p
if 'resume' in name:
resume_pdf = p
# Fallback names
if cover_pdf is None:
possible = output_dir / 'cover_letter.pdf'
if possible.exists():
cover_pdf = possible
if resume_pdf is None:
possible = output_dir / 'resume.pdf'
if possible.exists():
resume_pdf = possible
if cover_pdf is None or resume_pdf is None:
print_error('Could not locate both cover letter and resume PDFs to combine.')
return False
# Attempt to derive full name from personal details for consistent naming
try:
from cv_utils import extract_name_from_personal_details, ProjectPaths
paths = ProjectPaths()
full_name = extract_name_from_personal_details(paths.personal_details_file)
except Exception:
full_name = version
dest_name = f"{full_name} Cover Letter + Resume.pdf"
dest = output_dir / dest_name
res = combine_pdfs_via_latex(output_dir, cover_pdf, resume_pdf, dest)
if res:
print_success(f"Combined PDF created: {res.relative_to(Path.cwd())}")
return True
else:
print_error('Failed to create combined PDF')
return False
def refresh_vscode_tasks() -> bool:
"""Regenerate VS Code tasks.json.
Returns:
True if successful, False otherwise.
"""
print_header("Refresh VS Code Tasks")
try:
# Get available versions
versions = get_available_versions()
# Generate tasks JSON structure
tasks_dict = generate_tasks_json(versions)
# Write to .vscode/tasks.json
vscode_dir = Path.cwd() / '.vscode'
vscode_dir.mkdir(exist_ok=True)
tasks_file = vscode_dir / 'tasks.json'
with open(tasks_file, 'w', encoding='utf-8') as f:
json.dump(tasks_dict, f, indent=4, ensure_ascii=False)
print_success("VS Code tasks updated successfully!")
print_info(f"Updated {tasks_file.relative_to(Path.cwd())} with {len(versions)} versions")
return True
except Exception as e:
print_error(f"Failed to update tasks: {e}")
return False
def clean_build_artifacts(clean_all: bool = False) -> bool:
"""Clean LaTeX build artifacts and temporary files.
Args:
clean_all: If True, also removes PDFs and output directories
Returns:
True if successful, False otherwise.
"""
print_header("Clean Build Artifacts" if not clean_all else "Deep Clean")
base_path = Path.cwd()
# Patterns to clean
patterns = [
'*.aux', '*.log', '*.out', '*.toc', '*.fdb_latexmk',
'*.fls', '*.synctex.gz', '*.bbl', '*.blg', '*.bcf',
'*.run.xml', '*.idx', '*.ilg', '*.ind', '*.lof',
'*.lot', '*.nav', '*.snm', '*.vrb', '*.xdv'
]
# Add PDFs if doing full clean
if clean_all:
patterns.extend(['cv-*.pdf', '*.pdf'])
files_removed = []
print_info("Searching for build artifacts...")
for pattern in patterns:
for file in base_path.glob(pattern):
try:
file.unlink()
files_removed.append(file.name)
except Exception as e:
print_warning(f"Could not remove {file.name}: {e}")
# Clean __pycache__ directories
for pycache in base_path.rglob('__pycache__'):
try:
shutil.rmtree(pycache)
files_removed.append(str(pycache.relative_to(base_path)))
except Exception as e:
print_warning(f"Could not remove {pycache}: {e}")
# Clean output directory if doing full clean
if clean_all:
version = get_current_version()
if version:
output_dir = base_path / '_output' / version
if output_dir.exists():
print_info(f"Removing output directory: {output_dir.relative_to(base_path)}")
try:
shutil.rmtree(output_dir)
files_removed.append(f"_output/{version}/")
print_success("Removed output directory")
except Exception as e:
print_warning(f"Could not remove output directory: {e}")
# Clean symlinked package files in project root
texmf_dir = base_path / 'texmf'
if texmf_dir.exists():
print_info("Cleaning symlinked package files...")
for ext in ['*.sty', '*.cls', '*.def', '*.fd', '*.otf', '*.ttf', '*.pfb']:
for file in base_path.glob(ext):
# Check if it's a symlink or if the same file exists in texmf
if file.is_symlink() or (texmf_dir / file.name).exists():
try:
file.unlink()
files_removed.append(file.name)
except Exception as e:
print_warning(f"Could not remove {file.name}: {e}")
if files_removed:
print_success(f"Removed {len(files_removed)} artifact(s):")
for file in sorted(files_removed)[:10]: # Show first 10
print(f" - {file}")
if len(files_removed) > 10:
print(f" ... and {len(files_removed) - 10} more")
return True
else:
print_info("No artifacts found to clean")
return True
def validate_version(version: Optional[str] = None) -> bool:
"""Validate LaTeX files for common errors and control characters.
Args:
version: Version to validate. If None, validates current version.
Returns:
True if validation passed, False otherwise.
"""
if version is None:
version = get_current_version()
print_header(f"Validate Version: {version}")
content_dir = Path.cwd() / '_content' / version
if not content_dir.exists():
print_error(f"Version directory not found: {version}")
return False
tex_files = list(content_dir.glob('*.tex'))
if not tex_files:
print_warning(f"No .tex files found in {version}")
return True
errors_found = False
warnings_found = False
for tex_file in sorted(tex_files):
print(f"\n{Colors.BOLD}Checking {tex_file.name}:{Colors.ENDC}")
try:
content = tex_file.read_text(encoding='utf-8')
except UnicodeDecodeError:
print_error(" ✗ File encoding error - not valid UTF-8")
errors_found = True
continue
file_errors = []
file_warnings = []
# Check for control characters (except newline, tab, carriage return)
for i, line in enumerate(content.split('\n'), 1):
for j, char in enumerate(line, 1):
if ord(char) < 32 and char not in '\t\r':
file_errors.append(f" Line {i}, col {j}: Control character (ASCII {ord(char)})")
# Check for common LaTeX errors
lines = content.split('\n')
for i, line in enumerate(lines, 1):
# Unclosed braces (basic check)
open_braces = line.count('{') - line.count('\\{')
close_braces = line.count('}') - line.count('\\}')
if open_braces != close_braces:
file_warnings.append(f" Line {i}: Mismatched braces (may be multi-line)")
# Trailing whitespace
if line.endswith(' ') or line.endswith('\t'):
file_warnings.append(f" Line {i}: Trailing whitespace")
# Template placeholders still present
if '[' in line and ']' in line:
placeholders = re.findall(r'\[[A-Z][^\]]*\]', line)
if placeholders:
file_warnings.append(f" Line {i}: Template placeholder found: {placeholders[0]}")
# Common typos
if '\\begin{' in line:
env_match = re.search(r'\\begin\{([^}]+)\}', line)
if env_match:
env_name = env_match.group(1)
# Check if there's a matching \end
if f'\\end{{{env_name}}}' not in content:
file_warnings.append(f" Line {i}: \\begin{{{env_name}}} may be missing \\end{{{env_name}}}")
# Display results for this file
if file_errors:
print_error(f" Found {len(file_errors)} error(s):")
for error in file_errors[:5]: # Show first 5
print(error)
if len(file_errors) > 5:
print(f" ... and {len(file_errors) - 5} more")
errors_found = True
if file_warnings:
print_warning(f" Found {len(file_warnings)} warning(s):")
for warning in file_warnings[:5]: # Show first 5
print(warning)
if len(file_warnings) > 5:
print(f" ... and {len(file_warnings) - 5} more")
warnings_found = True
if not file_errors and not file_warnings:
print_success(" No issues found")
# Summary
print(f"\n{Colors.BOLD}Validation Summary:{Colors.ENDC}")
if errors_found:
print_error("Validation failed - errors found")
return False
elif warnings_found:
print_warning("Validation passed with warnings")
return True
else:
print_success("All files validated successfully!")
return True
def export_to_markdown(version: Optional[str] = None) -> bool:
"""Export version to markdown format.
Args:
version: Version to export. If None, uses current version.
Returns:
True if successful, False otherwise.
"""
if version is None:
version = get_current_version()
print_header(f"Export to Markdown: {version}")
try:
# Run resume_to_markdown
print_info("Converting resume to markdown...")
result = subprocess.run(
[sys.executable, str(SCRIPTS_DIR / 'resume_to_markdown.py')],
capture_output=True,
text=True
)
if result.returncode != 0:
print_error("Resume conversion failed")
if result.stderr:
print(result.stderr)
return False
print(result.stdout.strip())
# Check for cover letter
content_dir = Path.cwd() / '_content' / version
if (content_dir / 'cover_letter.tex').exists():
print_info("Converting cover letter to markdown...")
result = subprocess.run(
[sys.executable, str(SCRIPTS_DIR / 'cover_letter_to_markdown.py')],
capture_output=True,
text=True
)
if result.returncode != 0:
print_warning("Cover letter conversion failed")
else:
print(result.stdout.strip())
print_success("Markdown export complete!")
output_dir = Path.cwd() / '_output' / version
if output_dir.exists():
md_files = list(output_dir.glob('*.md'))
if md_files:
print(f"\n{Colors.BOLD}Exported files:{Colors.ENDC}")
for md_file in md_files:
print(f" - {md_file.relative_to(Path.cwd())}")
return True
except Exception as e:
print_error(f"Export failed: {e}")
return False
def duplicate_version(source: str, dest: Optional[str] = None) -> bool:
"""Duplicate an existing version.
Args:
source: Source version name
dest: Destination version name. If None, prompts user.
Returns:
True if successful, False otherwise.
"""
print_header("Duplicate Version")
content_dir = Path.cwd() / '_content'
source_dir = content_dir / source
# Check if source exists
if not source_dir.exists():
print_error(f"Source version '{source}' not found")
return False
# Get destination name
if dest is None:
print_info(f"Creating duplicate of: {Colors.CYAN}{source}{Colors.ENDC}")
dest = input(f"{Colors.BOLD}New version name: {Colors.ENDC}").strip()
if not dest:
print_error("Destination name cannot be empty")
return False
# Validate destination name
if not dest.replace('_', '').replace('-', '').isalnum():
print_error("Version name must contain only letters, numbers, underscores, and hyphens")
return False
dest_dir = content_dir / dest
# Check if destination exists
if dest_dir.exists():
print_error(f"Version '{dest}' already exists!")
return False
# Show preview
print(f"\n{Colors.BOLD}Preview:{Colors.ENDC}")
print(f" Source: {Colors.CYAN}{source}{Colors.ENDC}")
print(f" Destination: {Colors.CYAN}{dest}{Colors.ENDC}")
files = list(source_dir.glob('*.tex'))
print(f" Files to copy: {len(files)}")
# Confirm
confirm = input(f"\n{Colors.BOLD}Create duplicate? (y/N): {Colors.ENDC}").strip().lower()
if confirm != 'y':
print_info("Cancelled")
return False
# Copy
try:
shutil.copytree(source_dir, dest_dir)
print_success(f"Created duplicate: {dest}")
# Ask if user wants to switch to it
switch = input(f"\n{Colors.BOLD}Switch to this version now? (Y/n): {Colors.ENDC}").strip().lower()
if switch != 'n':
update_version(dest)
print_success(f"Switched to version: {dest}")
return True
except Exception as e:
print_error(f"Failed to duplicate: {e}")
return False