Project

General

Profile

Download (1.94 KB) Statistics
| Branch: | Tag: | Revision:

hammer-cli-csv / lib / hammer_cli_csv / locations.rb @ f92e695a

1
module HammerCLICsv
2
  class CsvCommand
3
    class LocationsCommand < BaseCommand
4
      command_name 'locations'
5
      desc         'import or export locations'
6

    
7
      PARENT = 'Parent Location'
8

    
9
      def export(csv)
10
        csv << [NAME, PARENT]
11
        @api.resource(:locations).call(:index, {
12
            :per_page => 999999,
13
            :search => option_search
14
        })['results'].each do |location|
15
          csv << [location['name'], '']
16
        end
17
      end
18

    
19
      def import
20
        @existing = {}
21
        @api.resource(:locations).call(:index, {:per_page => 999999})['results'].each do |location|
22
          @existing[location['name']] = location['id'] if location
23
        end
24

    
25
        thread_import do |line|
26
          create_locations_from_csv(line)
27
        end
28
      end
29

    
30
      def create_locations_from_csv(line)
31
        count(line[COUNT]).times do |number|
32
          name = namify(line[NAME], number)
33
          location_id = @existing[name]
34
          if !location_id
35
            print "Creating location '#{name}'... " if option_verbose?
36
            @api.resource(:locations).call(:create, {
37
                                             'location' => {
38
                                               'name' => name,
39
                                               'parent_id' => foreman_location(:name => line[PARENT])
40
                                             }
41
                                           })
42
          else
43
            print "Updating location '#{name}'... " if option_verbose?
44
            @api.resource(:locations).call(:update, {
45
                                             'id' => location_id,
46
                                             'location' => {
47
                                               'parent_id' => foreman_location(:name => line[PARENT])
48
                                             }
49
                                           })
50
          end
51
          print "done\n" if option_verbose?
52
        end
53
      end
54
    end
55
  end
56
end