summaryrefslogtreecommitdiff
path: root/lib/chef/knife/edit.rb
blob: 608ce82a8fc146e72b14cad3ea4b4275231ea424 (plain)
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
require "chef/chef_fs/knife"

class Chef
  class Knife
    class Edit < Chef::ChefFS::Knife
      banner "knife edit [PATTERN1 ... PATTERNn]"

      category "path-based"

      deps do
        require "chef/chef_fs/file_system"
        require "chef/chef_fs/file_system/not_found_error"
      end

      option :local,
        :long => "--local",
        :boolean => true,
        :description => "Show local files instead of remote"

      def run
        # Get the matches (recursively)
        error = false
        pattern_args.each do |pattern|
          Chef::ChefFS::FileSystem.list(config[:local] ? local_fs : chef_fs, pattern).each do |result|
            if result.dir?
              ui.error "#{format_path(result)}: is a directory" if pattern.exact_path
              error = true
            else
              begin
                new_value = edit_text(result.read, File.extname(result.name))
                if new_value
                  result.write(new_value)
                  output "Updated #{format_path(result)}"
                else
                  output "#{format_path(result)} unchanged!"
                end
              rescue Chef::ChefFS::FileSystem::OperationNotAllowedError => e
                ui.error "#{format_path(e.entry)}: #{e.reason}."
                error = true
              rescue Chef::ChefFS::FileSystem::NotFoundError => e
                ui.error "#{format_path(e.entry)}: No such file or directory"
                error = true
              end
            end
          end
        end
        if error
          exit 1
        end
      end

      def edit_text(text, extension)
        if (!config[:disable_editing])
          Tempfile.open([ "knife-edit-", extension ]) do |file|
            # Write the text to a temporary file
            file.write(text)
            file.close

            # Let the user edit the temporary file
            if !system("#{config[:editor]} #{file.path}")
              raise "Please set EDITOR environment variable"
            end

            result_text = IO.read(file.path)

            return result_text if result_text != text
          end
        end
      end
    end
  end
end