]> git.openstreetmap.org Git - chef.git/blob - cookbooks/nodejs/resources/package.rb
886d486e1c0e61515877fd05670189f24122e0be
[chef.git] / cookbooks / nodejs / resources / package.rb
1 #
2 # Cookbook Name:: nodejs
3 # Resource:: package
4 #
5 # Copyright 2013, OpenStreetMap Foundation
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
10 #
11 # https://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18 #
19
20 require "chef/mixin/shell_out"
21 require "json"
22
23 default_action :install
24
25 property :package, :kind_of => String, :name_attribute => true
26 property :version, :kind_of => String
27
28 action :install do
29   qualified_name = if new_resource.version
30                      "#{new_resource.package}@#{new_resource.version}"
31                    else
32                      new_resource.package
33                    end
34
35   if current_version.nil?
36     converge_by "install #{qualified_name}" do
37       shell_out!("npm install --global #{qualified_name}")
38     end
39   elsif new_resource.version &&
40         new_resource.version != current_version
41     converge_by "update #{qualified_name}" do
42       shell_out!("npm install --global #{qualified_name}")
43     end
44   end
45 end
46
47 action :upgrade do
48   unless current_version.nil?
49     converge_by "update #{new_resource.package}" do
50       shell_out!("npm update --global #{new_resource.package}")
51     end
52   end
53 end
54
55 action :remove do
56   unless current_version.nil?
57     converge_by "remove #{new_resource.package}" do
58       shell_out!("npm remove --global #{new_resource.package}")
59     end
60   end
61 end
62
63 action_class do
64   include Chef::Mixin::ShellOut
65
66   def current_version
67     @current_version ||= JSON.parse(shell_out("npm list --global --json").stdout)
68                              .dig("dependencies", new_resource.package, "version")
69   end
70 end