Skip to content

Instantly share code, notes, and snippets.

@x1024
Created May 9, 2013 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save x1024/3d0f9ad61fcb4b189be3 to your computer and use it in GitHub Desktop.
Save x1024/3d0f9ad61fcb4b189be3 to your computer and use it in GitHub Desktop.
require 'awesome_print'
require 'pp'
input = <<TEXT
2 1 app/assets/javascripts/bar.js
16 25 app/assets/javascripts/baz.js.coffee
1 1 app/assets/javascripts/foo.js.coffee
4 9 app/controllers/bar_controller.rb
3 2 app/controllers/baz_controller.rb
11 0 app/controllers/foo_controller.rb
3 2 db/schema.rb
41 1 lib/foobar.rb
12 7 lib/tasks/cache.rake
5 13 lib/tasks/import.rake
TEXT
# totals: add: 98, del: 61
expected =
[
{ name: "app",
add: 37,
del: 38,
children: [
{name: "assets", add: 19, del: 27, children: [
{name: "javascripts", add: 19, del: 27, children: [
{name: "bar.js", add: 2, del: 1},
{name: "baz.js.coffee", add: 16, del: 25},
{name: "foo.js.coffee", add: 1, del: 1}
]
},
]
},
{name: "controllers", add: 18, del: 11, children: [
{name: "bar_controller.rb", add: 4, del: 9},
{name: "baz_controller.rb", add: 3, del: 2},
{name: "foo_controller.rb", add: 11, del: 0},
]
},
]
},
{ add: 3,
del: 2,
name: "db",
children: [ {name: "schema.rb", add: 3, del: 2} ]
},
{ add: 58,
del: 21,
name: "lib",
children: [
{name: "foobar.rb", add: 41, del: 1},
{name: "tasks", add: 17, del: 20, children:
[ {name: "cache.rake", add: 12, del: 7},
{name: "import.rake", add: 5, del: 13} ] }
]
}
]
def git_group lines, root = 'root'
if lines.count == 1 and lines[0][:name].empty? then
return {
name: root,
add: lines.map { |l| l[:add] }.reduce(0, :+),
del: lines.map { |l| l[:del] }.reduce(0, :+),
}
end
lines = lines.group_by { |line| line[:name].shift }
.map { |key, value| git_group(value, key) }
return {
name: root,
add: lines.map { |l| l[:add] }.reduce(0, :+),
del: lines.map { |l| l[:del] }.reduce(0, :+),
children: lines
}
end
def to_git_diffnum_tree(txt)
data = txt.split("\n")
.map { |line| line.split() }
.map { |line| {add: line[0].to_i, del: line[1].to_i, name: line[2].split('/')} }
.sort_by { |item| item[:name] }
git_group(data)[:children]
end
out = to_git_diffnum_tree(input)
puts; ap out; puts
puts; puts "Expected result:"; puts expected.inspect
puts; puts "Actual result: "; puts out.inspect
puts; puts "Are expected and actual results identical: #{expected == out}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment