Class: Workspace

Inherits:
Object
  • Object
show all
Defined in:
lib/workspace.rb

Constant Summary collapse

MissingFile =
Class.new(StandardError)
NoPermission =
Class.new(StandardError)
IGNORE =
[".", "..", ".git"]

Instance Method Summary collapse

Constructor Details

#initialize(pathname) ⇒ Workspace

Returns a new instance of Workspace.



9
10
11
# File 'lib/workspace.rb', line 9

def initialize(pathname)
  @pathname = pathname
end

Instance Method Details

#apply_migration(migration) ⇒ Object



69
70
71
72
73
74
75
76
# File 'lib/workspace.rb', line 69

def apply_migration(migration)
  apply_change_list(migration, :delete)
  migration.rmdirs.sort.reverse_each { |dir| remove_directory(dir) }

  migration.mkdirs.sort.each { |dir| make_directory(dir) }
  apply_change_list(migration, :update)
  apply_change_list(migration, :create)
end

#list_dir(dirname) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/workspace.rb', line 26

def list_dir(dirname)
  path    = @pathname.join(dirname || "")
  entries = Dir.entries(path) - IGNORE
  stats   = {}

  entries.each do |name|
    relative = path.join(name).relative_path_from(@pathname)
    stats[relative.to_s] = File.stat(path.join(name))
  end

  stats
end

#list_files(path = @pathname) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/workspace.rb', line 13

def list_files(path = @pathname)
  relative = path.relative_path_from(@pathname)

  if File.directory?(path)
    filenames = Dir.entries(path) - IGNORE
    filenames.flat_map { |name| list_files(path.join(name)) }
  elsif File.exist?(path)
    [relative]
  else
    raise MissingFile, "pathspec '#{ relative }' did not match any files"
  end
end

#read_file(path) ⇒ Object



39
40
41
42
43
# File 'lib/workspace.rb', line 39

def read_file(path)
  File.read(@pathname.join(path))
rescue Errno::EACCES
  raise NoPermission, "open('#{ path }'): Permission denied"
end

#remove(path) ⇒ Object



63
64
65
66
67
# File 'lib/workspace.rb', line 63

def remove(path)
  FileUtils.rm_rf(@pathname.join(path))
  path.dirname.ascend { |dirname| remove_directory(dirname) }
rescue Errno::ENOENT
end

#stat_file(path) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/workspace.rb', line 45

def stat_file(path)
  File.stat(@pathname.join(path))
rescue Errno::ENOENT, Errno::ENOTDIR
  nil
rescue Errno::EACCES
  raise NoPermission, "stat('#{ path }'): Permission denied"
end

#write_file(path, data, mode = nil, mkdir = false) ⇒ Object



53
54
55
56
57
58
59
60
61
# File 'lib/workspace.rb', line 53

def write_file(path, data, mode = nil, mkdir = false)
  full_path = @pathname.join(path)
  FileUtils.mkdir_p(full_path.dirname) if mkdir

  flags = File::WRONLY | File::CREAT | File::TRUNC
  File.open(full_path, flags) { |f| f.write(data) }

  File.chmod(mode, full_path) if mode
end