Digital Magpie

Ooh, ooh, look - shiny things!

Category Counts in OctoPress Revisited

As an improvement on an older shell script, here’s a rake task to list all of the categories in your blog, along with post counts for each of them:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
desc "count the number of posts in each category"
task :count_categories do
  require 'yaml'

  counts = {}

  Dir.glob('source/_posts/*.markdown').each do |f|
    post = begin
      YAML.load(File.open(f))
    rescue ArgumentError => e
      puts "error: parsing #{f} - #{e.message}"
    end
    cats = post['categories']
    if cats.respond_to? "each"
      cats.each {|c| counts[c] = counts[c].to_i + 1}
    else
      counts[cats] = counts[cats].to_i + 1
    end
  end

  counts.sort_by {|k,v| v}.reverse.each {|k,v| puts "#{v} #{k}"}
end

Just add this to the end of your OctoPress Rakefile and you’re good to go.

Comments