#!/usr/bin/env ruby # frozen_string_literal: true require 'json' require 'optparse' require 'pathname' require 'time' options = { target: Pathname.new('histories'), dry_run: false, verbose: false } OptionParser.new do |opts| opts.banner = 'Usage: ruby scripts/sort_histories.rb [options]' opts.on('-t', '--target PATH', '対象のディレクトリまたは JSONL ファイル (default: histories)') do |path| options[:target] = Pathname.new(path) end opts.on('--dry-run', 'ファイルを書き換えずに変更対象のみ確認する') do options[:dry_run] = true end opts.on('-v', '--verbose', '処理するファイル名を表示する') do options[:verbose] = true end end.parse! target_path = options[:target].expand_path unless target_path.exist? warn "対象が見つかりません: #{target_path}" exit 1 end jsonl_files = if target_path.file? [target_path] else Dir.glob(target_path.join('**/*.jsonl').to_s).map { |path| Pathname.new(path) }.sort end if jsonl_files.empty? warn "JSONL ファイルが見つかりません: #{target_path}" exit 1 end def load_entries(path) File.readlines(path, chomp: true).each_with_index.filter_map do |line, idx| next if line.strip.empty? JSON.parse(line) rescue JSON::ParserError => e warn "JSON パースに失敗しました (#{path}:#{idx + 1}): #{e.message}" nil end end def sort_entries(entries) entries.each_with_index.sort_by do |entry, idx| raw_date = entry['date'].to_s parsed_time = begin Time.strptime(raw_date, '%Y-%m-%d %H:%M:%S') rescue StandardError begin Time.parse(raw_date) rescue StandardError Time.at(0) end end [parsed_time, idx] end.map(&:first) end changed_files = [] jsonl_files.each do |path| original_content = File.read(path) entries = load_entries(path) sorted_entries = sort_entries(entries) sorted_content = sorted_entries.map { |entry| JSON.generate(entry) }.join("\n") sorted_content += "\n" unless sorted_content.empty? next if sorted_content == original_content changed_files << path if options[:dry_run] puts "変更予定: #{path}" if options[:verbose] next end puts "更新: #{path}" if options[:verbose] File.write(path, sorted_content) end message = if options[:dry_run] "書き込みなしで完了。変更対象: #{changed_files.size}件" else "完了。更新: #{changed_files.size}件" end puts message