-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathz.rb
More file actions
76 lines (61 loc) · 2.41 KB
/
Copy pathz.rb
File metadata and controls
76 lines (61 loc) · 2.41 KB
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
# Since we can't change the current shell directory from a script, this only outputs the new
# directory. Please see README for instructions.
$LOAD_PATH << File.join(File.dirname(__FILE__))
require 'util'
Z_FILE = File.join(ENV['HOME'], '.compnav-z').freeze
Z_HEADER = 'compnav-z'.freeze
Z_VERSION = '0.0.1'.freeze
# compnav used to store its list in ~/.z, which clashes with the database of the original z
# utility (and used to silently overwrite it). Migrate a compnav-created ~/.z to the new
# location; a ~/.z belonging to another tool is left alone.
old_z_file = File.join(ENV['HOME'], '.z')
if !File.file?(Z_FILE) && File.file?(old_z_file)
header = File.open(old_z_file, 'r') { |file| file.gets }
if !header.nil? && header.start_with?(Z_HEADER)
File.rename(old_z_file, Z_FILE)
end
end
def read_z_dirs(dir_to_skip)
z_dirs = []
if File.file?(Z_FILE)
File.open(Z_FILE, 'r') do |file|
# Check the header. If the file wasn't created by compnav, ignore its contents
# (it will be overwritten on the next --add).
header = file.gets
if !header.nil? && header.start_with?(Z_HEADER)
# Read all lines from the file, removing our dir if it is present.
# We add our dir to the end of the file later.
z_dirs = file
.map { |line| line.chomp }
.filter { |line| !line.strip.empty? && line != dir_to_skip }
end
end
end
z_dirs
end
return if defined? REQUIRING_Z
if ARGV.length == 2 && ARGV[0] == '--add'
# Add the passed-in dir to the recent-dirs list as the most recent one (last line of .z).
# Remove any trailing slashes
dir_to_add = ARGV[1].chomp('/')
z_dirs = read_z_dirs dir_to_add
# Write to a temp file and rename it into place. Every open shell writes this file on
# every cd; the atomic rename ensures a concurrent reader or writer never sees a
# partially-written list.
tmp_file = "#{Z_FILE}.#{Process.pid}.tmp"
File.open(tmp_file, 'w') do |file|
file.write "#{Z_HEADER} #{Z_VERSION}\n"
z_dirs.each { |z_dir| file.write "#{z_dir}\n" }
file.write "#{dir_to_add}\n"
end
File.rename(tmp_file, Z_FILE)
exit
end
z_dirs = read_z_dirs(PWD).map { |z_dir| path_with_tilde(z_dir) }.join("\n")
# Nothing to offer: exit nonzero (and print nothing) so the shell wrapper skips the cd.
exit 1 if z_dirs.empty?
if ARGV.length >= 1 && ARGV[0] == '--fzf'
pipe_to_fzf_and_print(z_dirs, true, 'COMPNAV_FZF_Z_OPTS')
else
puts z_dirs
end