File size: 2,516 Bytes
f83e695
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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