|
| 1 | +#!/usr/bin/perl |
| 2 | + |
| 3 | +use strict; |
| 4 | +use warnings; |
| 5 | + |
| 6 | +# Check if two arguments are provided |
| 7 | +die "Usage: $0 <template-file> <content-directory>\n" unless @ARGV == 2; |
| 8 | + |
| 9 | +my ($template_file, $content_dir) = @ARGV; |
| 10 | + |
| 11 | +# Check if the template file exists and is readable |
| 12 | +die "Template file does not exist or cannot be read.\n" unless -f $template_file && -r $template_file; |
| 13 | + |
| 14 | +# Check if the content directory exists and is a directory |
| 15 | +die "Content directory does not exist or is not a directory.\n" unless -d $content_dir; |
| 16 | + |
| 17 | +# Read the entire template file into a string |
| 18 | +open my $template_fh, '<', $template_file or die "Cannot open template file: $!\n"; |
| 19 | +local $/; # Enable slurp mode to read the whole file at once |
| 20 | +my $template_content = <$template_fh>; |
| 21 | +close $template_fh; |
| 22 | + |
| 23 | +# Process each file in the content directory |
| 24 | +opendir my $dir, $content_dir or die "Cannot open directory: $!\n"; |
| 25 | +while (my $file = readdir($dir)) { |
| 26 | + next if $file =~ /^\.\.?$/; # Skip . and .. |
| 27 | + my $file_path = "$content_dir/$file"; |
| 28 | + next unless -f $file_path; # Skip if not a file |
| 29 | + |
| 30 | + # Read file content |
| 31 | + open my $file_fh, '<', $file_path or die "Cannot open $file_path: $!\n"; |
| 32 | + local $/; # Enable slurp mode |
| 33 | + my $file_content = <$file_fh>; |
| 34 | + close $file_fh; |
| 35 | + |
| 36 | + # Escape special characters in file content for safe replacement |
| 37 | + $file_content =~ s/([\$\@])/\\$1/g; |
| 38 | + |
| 39 | + # Replace placeholders in the template |
| 40 | + $template_content =~ s/\{\{\Q$file\E\}\}/$file_content/g; |
| 41 | +} |
| 42 | +closedir $dir; |
| 43 | + |
| 44 | +# Output the processed template |
| 45 | +print $template_content; |
0 commit comments