Project

General

Profile

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

hammer-cli-csv / lib / hammer_cli_csv / organizations.rb @ c06f1783

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

    
7
      LABEL = 'Label'
8
      DESCRIPTION = 'Description'
9

    
10
      def export(csv)
11
        csv << [NAME, LABEL, DESCRIPTION]
12

    
13
        if @server_status['release'] == 'Headpin'
14
          @headpin.get(:organizations).each do |organization|
15
            next if option_organization && organization['name'] != option_organization
16
            csv << [organization['name'], organization['label'], organization['description']]
17
          end
18
        else
19
          @api.resource(:organizations).call(:index, {:per_page => 999999})['results'].each do |organization|
20
            next if option_organization && organization['name'] != option_organization
21
            csv << [organization['name'], organization['label'], organization['description']]
22
          end
23
        end
24
      end
25

    
26
      def import
27
        @existing = {}
28
        @api.resource(:organizations).call(:index, {:per_page => 999999})['results'].each do |organization|
29
          @existing[organization['name']] = organization['id'] if organization
30
        end
31

    
32
        thread_import do |line|
33
          create_organizations_from_csv(line)
34
        end
35
      end
36

    
37
      def create_organizations_from_csv(line)
38
        count(line[COUNT]).times do |number|
39
          name = namify(line[NAME], number)
40
          return if option_organization && name != option_organization
41
          label = namify(line[LABEL], number)
42
          organization_id = @existing[name]
43
          if organization_id.nil?
44
            print "Creating organization '#{name}'... " if option_verbose?
45
            @api.resource(:organizations).call(:create, {
46
                'name' => name,
47
                'organization' => {
48
                    'name' => name,
49
                    'label' => label,
50
                    'description' => line[DESCRIPTION]
51
                }
52
            })
53
          else
54
            print "Updating organization '#{name}'... " if option_verbose?
55
            organization = @api.resource(:organizations).call(:show, {'id' => organization_id})
56
            @api.resource(:organizations).call(:update, {
57
                'id' => organization_id,
58
                'organization' => {
59
                    'id' => organization_id,
60
                    'description' => line[DESCRIPTION]
61
                }
62
            })
63
          end
64
          print "done\n" if option_verbose?
65
        end
66
      end
67
    end
68
  end
69
end