-
Notifications
You must be signed in to change notification settings - Fork 0
/
modulist
executable file
·97 lines (69 loc) · 2.11 KB
/
modulist
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
#!/usr/bin/env ruby -w
# A portmanteau of "module" and "list". Stashes the homebrew formulae and gems
# installed on a given host to a timestamped, host-specific file in
# ~/.config/modulist.
#
# (File under "hack and a half", but it serves its purpose.)
require 'Date'
require 'FileUtils'
class Stash
attr_accessor :stash_root
def initialize
@typemap = {
'gems' => {
command: 'gem',
flags: '--no-version'
}
}
@stash_root= '~/.config/modulist'
@stash_path = File.expand_path(@stash_root)
FileUtils.mkdir_p(@stash_path)
end
# Return the tail end of a basename. This is separate from full_path because
# we also use the tail end as part of a glob for the `purge` step below.
def name_tail(type)
hostname = %x(hostname -s).chomp
[hostname, type].join('_') + '.txt'
end
# Given the name of a type, return an absolute path, in the dedicated
# directory, to a file whose name incorporates the date, base hostname, and
# type.
def full_path(type)
date = Date.today.to_s
basename = [date, name_tail(type)].join('_')
File.join(@stash_path, basename)
end
# Given the name of a type (e.g. "brew", "gem"), write a list of currently-
# installed instances to a file.
def store(type)
latest = full_path(type)
command = type
flags = ''
# This is so wrong that the hell it earns me has yet to be defined.
if mapping = @typemap[type]
command = mapping[:command] || type
flags = mapping[:flags] || ''
end
items = %x(#{command} list #{flags})
puts "#{type}: #{items.split.count}"
File.open(latest, "w") do |handle|
handle.write(items)
end
end
# Clean up by deleting all but the most recent stash for this host and type.
def purge(type)
fileset = Dir.glob(File.join(@stash_path, "*#{name_tail(type)}")).sort
fileset.pop
fileset.each do |file|
FileUtils.rm(file)
end
end
end
# --------------------
stash = Stash.new
types = %w[brew gems]
puts "Updating brew and gem lists in #{stash.stash_root}"
types.each do |type|
stash.store(type)
stash.purge(type)
end