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
|
11
|
CSV.open(option_file || '/dev/stdout', 'wb', {:force_quotes => true}) do |csv|
|
12
|
csv << [NAME, COUNT, LABEL, DESCRIPTION]
|
13
|
|
14
|
if @server_status['release'] == 'Headpin'
|
15
|
@headpin.get(:organizations).each do |organization|
|
16
|
next if option_organization && organization['name'] != option_organization
|
17
|
csv << [organization['name'], 1, organization['label'], organization['description']]
|
18
|
end
|
19
|
else
|
20
|
@api.resource(:organizations).call(:index, {:per_page => 999999})['results'].each do |organization|
|
21
|
next if option_organization && organization['name'] != option_organization
|
22
|
csv << [organization['name'], 1, organization['label'], organization['description']]
|
23
|
end
|
24
|
end
|
25
|
end
|
26
|
end
|
27
|
|
28
|
def import
|
29
|
@existing = {}
|
30
|
@api.resource(:organizations).call(:index, {:per_page => 999999})['results'].each do |organization|
|
31
|
@existing[organization['name']] = organization['id'] if organization
|
32
|
end
|
33
|
|
34
|
thread_import do |line|
|
35
|
create_organizations_from_csv(line)
|
36
|
end
|
37
|
end
|
38
|
|
39
|
def create_organizations_from_csv(line)
|
40
|
line[COUNT].to_i.times do |number|
|
41
|
name = namify(line[NAME], number)
|
42
|
return if option_organization && name != option_organization
|
43
|
label = namify(line[LABEL], number)
|
44
|
if !@existing.include? name
|
45
|
print "Creating organization '#{name}'... " if option_verbose?
|
46
|
@api.resource(:organizations).call(:create, {
|
47
|
'name' => name,
|
48
|
'organization' => {
|
49
|
'name' => name,
|
50
|
'label' => label,
|
51
|
'description' => line[DESCRIPTION]
|
52
|
}
|
53
|
})
|
54
|
else
|
55
|
print "Updating organization '#{name}'... " if option_verbose?
|
56
|
@api.resource(:organizations).call(:update, {
|
57
|
'id' => foreman_organization(:name => name),
|
58
|
'organization' => {
|
59
|
'id' => foreman_organization(:name => name),
|
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
|