#!/usr/bin/env ruby # frozen_string_literal: true require 'fileutils' # Define your source and destination directories source_dir = 'content/blog' posts_destination_dir = 'src/_posts' images_destination_dir = 'src/images' # Make sure the destination directories exist FileUtils.mkdir_p(posts_destination_dir) unless Dir.exist?(posts_destination_dir) FileUtils.mkdir_p(images_destination_dir) unless Dir.exist?(images_destination_dir) # Regex to match Markdown image paths excluding absolute URLs markdown_img_regex = /!\[\]\(((?!http:\/\/|https:\/\/)[^)]+)\)/ # List all directories within the source directory Dir.glob("#{source_dir}/*").select { |f| File.directory?(f) }.each do |dir| # Get the name of the directory dir_name = File.basename(dir) # For migrating assets, check if there are files in the directory if Dir.glob("#{dir}/*").any? { |f| File.file?(f) && !f.end_with?('index.md') } # Construct the destination directory path for images destination_images_dir = File.join(images_destination_dir, dir_name) # Move the entire directory (which now only contains assets) Dir.glob("#{dir}/*").each do |file| # Skip the index.md file next if File.basename(file) == 'index.md' # Ensure destination directory exists FileUtils.mkdir_p(destination_images_dir) unless Dir.exist?(destination_images_dir) # Move each file FileUtils.mv(file, File.join(destination_images_dir, File.basename(file))) end puts "Moved assets from #{dir} to #{destination_images_dir}" end # For migrating Markdown files # Construct the source file path source_file = File.join(dir, 'index.md') # Construct the destination file path for posts destination_post_file = File.join(posts_destination_dir, "#{dir_name}.md") # Migrate and update Markdown file if it exists if File.exist?(source_file) # Read the content of the Markdown file content = File.read(source_file) # Replace image paths in the content content = content.gsub(markdown_img_regex) do |match| "![](/images/#{dir_name}/#{$1})" end # Add layout to the frontmatter content.sub!(/^---/, "---\nlayout: post") # Write the updated content to the new destination File.write(destination_post_file, content) FileUtils.rm(source_file) # Remove the original Markdown file puts "Updated and moved #{source_file} to #{destination_post_file}" end end puts "Migration and update completed."