summaryrefslogtreecommitdiff
path: root/contrib/sort_includes.rb
blob: c9f7076c9eb3a4a54b26e1ef6950520466865990 (plain)
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
#!/usr/bin/env ruby

def is_include str
  str.start_with? '#include'
end

files = ARGV
if files.empty?
  default = "src/**/*.[ch]"
  puts "no arguments passed, defaulting to #{default}"
  files = Dir[default]
end

files.each { |path|
  File.open(path, "r+") do |file|
    lines = file.readlines

    last = nil
    grouped = []
    lines.each do |line|
      if is_include(line) != last
        grouped << [line]
        last = is_include(line)
      else
        grouped[-1] << line
      end
    end

    grouped.map do |group|
      group.sort! if is_include group[0]
    end
    grouped = grouped.flatten

    next if grouped == lines

    puts path
    file.truncate(0)
    file.seek(0)
    file.write grouped.join
  end
}