Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/tools/dev/find_and_replace_dead_reference_links.rb
Views: 17951
##1#2# tools/dev/detect_dead_reference_links.rb must be run before this script as it will3# create the url_check_results.json file that is used to run the script.4#5# Usage: ruby tools/dev/find_and_replace_dead_reference_links.rb -f url_check_results.json6#7##89require 'json'10require 'fileutils'1112# Loads JSON data from the specified file.13# @param file_path [String] the path to the JSON file to load.14# @return [Array] parsed JSON data.15# @raise [Errno::ENOENT] if the file cannot be found.16# @raise [JSON::ParserError] if the JSON is malformed.17def load_json(file_path)18JSON.parse(File.read(file_path))19end2021# Replaces the original URLs with archived snapshots in the content of files.22# This method processes each entry in the provided data, and if a valid23# archived snapshot is available, it replaces the URL in the corresponding file.24# @param data [Array] the array of data containing URL and archived_snapshot pairs.25# @return [void]26def replace_links_in_files(data)27data.each_with_index do |entry, index|28puts "Processing entry #{index + 1}: #{entry['url']} -> #{entry['archived_snapshot']}"2930url = entry['url'].sub(/^URL-/, '')31path = entry['path']32archived_snapshot = entry['archived_snapshot']3334# Skip entries with no archived version or errors fetching the snapshot35if archived_snapshot == 'No archived version found' || archived_snapshot.nil? || archived_snapshot.start_with?('Error fetching Wayback')36puts "Skipping entry #{index + 1} because no archived version is available or there was an error fetching it."37next38end3940# Construct full file path and check if file exists41full_path = File.join(Dir.pwd, path)4243if File.exist?(full_path)44file_content = File.read(full_path)4546# Replace the original URL with the archived snapshot47updated_content = file_content.gsub(url, archived_snapshot)4849# Write changes back to the file if any replacements were made50if file_content != updated_content51File.open(full_path, 'w') { |file| file.write(updated_content) }52puts "Replaced URL in file: #{full_path}"53else54puts "No change needed for file: #{full_path}"55end56else57puts "File not found: #{full_path}"58end59end60end6162begin63# Load the JSON data from the file 'url_check_results.json'64json_data = load_json('url_check_results.json')6566# Replace the URLs in files based on the loaded data67replace_links_in_files(json_data)68rescue StandardError => e69# Handle errors gracefully and provide meaningful feedback70puts "An error occurred: #{e.message}"71end727374