Module: TargetIO::Support

Included in:
TrainCompat::Dir, TrainCompat::File, TrainCompat::FileUtils, TrainCompat::HTTP
Defined in:
lib/chef/target_io/support.rb

Instance Method Summary collapse

Instance Method Details

#clean_staging(filename) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/chef/target_io/support.rb', line 49

def clean_staging(filename)
  ::TargetIO::FileUtils.rm(filename)

  staging_dir = ::File.dirname(filename)
  ::TargetIO::FileUtils.rmdir(staging_dir)
rescue Errno::ENOENT
end

#read_file(filename) ⇒ Object

"sudo" based connections need a staging area for file reading/writing



6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/chef/target_io/support.rb', line 6

def read_file(filename)
  accessible_file = filename

  if sudo?
    accessible_file = staging_file(filename)
    ::TargetIO::FileUtils.cp(filename, accessible_file)
  end

  content = transport_connection.file(accessible_file).content

  clean_staging(accessible_file) if sudo?

  content
end

#remote_userObject



65
66
67
# File 'lib/chef/target_io/support.rb', line 65

def remote_user
  transport_connection.transport_options[:user]
end

#run_command(cmd) ⇒ Object



57
58
59
# File 'lib/chef/target_io/support.rb', line 57

def run_command(cmd)
  transport_connection.run_command(cmd)
end

#staging_file(filename) ⇒ Object



44
45
46
47
# File 'lib/chef/target_io/support.rb', line 44

def staging_file(filename)
  staging_dir = ::TargetIO::Dir.mktmpdir(filename)
  ::File.join(staging_dir, ::File.basename(filename))
end

#sudo?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/chef/target_io/support.rb', line 61

def sudo?
  transport_connection.transport_options[:sudo]
end

#transport_connectionObject



69
70
71
# File 'lib/chef/target_io/support.rb', line 69

def transport_connection
  Chef.run_context&.transport_connection
end

#upload(local_file, remote_file) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/chef/target_io/support.rb', line 32

def upload(local_file, remote_file)
  accessible_file = remote_file
  accessible_file = staging_file(remote_file) if sudo?

  transport_connection.upload(local_file, accessible_file)

  if sudo?
    ::TargetIO::FileUtils.mv(accessible_file, remote_file)
    clean_staging(accessible_file)
  end
end

#write_file(remote_file, content) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/chef/target_io/support.rb', line 21

def write_file(remote_file, content)
  tempfile = ::Tempfile.new
  tempfile.write(tempfile, content)
  tempfile.close

  upload(tempfile.path, remote_file)
  tempfile.unlink

  remote_file
end