-
Notifications
You must be signed in to change notification settings - Fork 1
/
dotdotdot.rb
executable file
·101 lines (86 loc) · 2.47 KB
/
dotdotdot.rb
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
#!/usr/bin/env ruby
require 'psych'
require 'pathname'
require 'fileutils'
class Dotdotdot
def initialize
@backup_directory = File.join(Dir.pwd, 'backups')
@lib_directory = File.join(Dir.pwd, 'lib')
@config = Psych::load(File.open('etc/config.yml'))
dotfiles = @config["dotfiles"]
dotfiles.instance_eval do
def return_keys(bool)
self.select { | k, v | v == bool }
end
end
unless File.exist?(@backup_directory)
Dir.mkdir(@backup_directory)
end
@enabled = dotfiles.return_keys(true)
@disabled = dotfiles.return_keys(false)
@all = @disabled.merge(@enabled)
puts "> enabling #{@enabled.keys}"
puts "> disabling #{@disabled.keys}"
backup_symlinks
disable_symlinks
enable_symlinks
cleanup_backups
end
def backup_symlinks
backup = String.new
@all.each do | key, value |
target = File.join(Dir.home, ".#{Pathname.new(key).basename}")
if File.exist?(target)
backup << ".#{Pathname.new(key).basename} "
end
end
unless backup.empty?
current = Dir.pwd
system "cd ~ && tar -czf #{current}/backups/dotdotdot_backup_#{Time.now.to_i}.tgz #{backup}"
end
end
def disable_symlinks
@all.each do | key, value |
target = File.join(Dir.home, ".#{Pathname.new(key).basename}")
begin
if File.directory?(target)
FileUtils::remove_dir(target)
elsif File.exists?(target)
File.unlink(target)
end
rescue Exception => e
puts e
end
end
end
def enable_symlinks
@enabled.each do | key, value |
target = File.join(Dir.pwd, "lib", key)
if File.exist?(target)
puts "> symlinking .#{Pathname.new(key).basename}"
FileUtils.ln_sf(target, (File.join(Dir.home, ".#{Pathname.new(key).basename}")))
end
end
end
def cleanup_backups
keep = @config["keep_backups"].to_i
backup_list = Array.new
Dir.foreach(@backup_directory) do | file |
unless File.directory?(File.join(@backup_directory, file))
backup_list << file
end
end
backup_list.reject! { | file | file[0] == "." } # ditch hidden files
if backup_list.length > keep
backup_list.first(backup_list.length - keep).each do | file |
file = File.join(@backup_directory, file)
begin
File.delete(file)
rescue Exception => e
puts e
end
end
end
end
end
d = Dotdotdot.new