-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsyntax-check.rb
106 lines (96 loc) · 3 KB
/
syntax-check.rb
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
require 'chef/knife'
module KnifePlugin
class SyntaxCheck < Chef::Knife
banner "knife syntax-check"
option :environments,
:short => '-e',
:long => '--environments',
:boolean => true,
:description => "Test only environment syntax"
option :roles,
:short => '-r',
:long => '--roles',
:boolean => true,
:description => "Test only role syntax"
option :nodes,
:short => '-n',
:long => '--nodes',
:boolean => true,
:description => "Test only node syntax"
option :databags,
:short => '-D',
:long => '--databags',
:boolean => true,
:description => "Test only databag syntax"
option :cookbooks,
:short => '-c',
:long => '--cookbooks',
:boolean => true,
:description => "Test only cookbook syntax"
option :all,
:short => '-a',
:long => '--all',
:boolean => true,
:description => "Test syntax of all roles, environments, nodes, databags and cookbooks"
deps do
require 'yajl'
require 'pathname'
end
def run
if config[:roles]
test_object("roles/*", "role")
elsif config[:environments]
test_object("environments/*", "environment")
elsif config[:nodes]
test_object("nodes/*", "node")
elsif config[:databags]
test_databag("data_bags/*", "data bag")
elsif config[:cookbooks]
test_cookbooks()
elsif config[:all]
test_object("roles/*", "role")
test_object("environments/*", "environment")
test_object("nodes/*", "node")
test_databag("data_bags/*", "data bag")
test_cookbooks()
else
ui.msg("Usage: knife syntax-check --help")
end
end
# Test all cookbooks
def test_cookbooks()
ui.msg("Testing all cookbooks...")
system("knife cookbook test --all") or raise "Syntax check of all cookbooks failed!"
end
# Test object syntax
def test_object(dirname,type)
ui.msg("Finding type #{type} to test from #{dirname}")
check_syntax(dirname,nil,type)
end
# Test databag syntax
def test_databag(dirname, type)
ui.msg("Finding type #{type} to test from #{dirname}")
dirs = Dir.glob(dirname).select { |d| File.directory?(d) }
dirs.each do |directory|
dir = Pathname.new(directory).basename
check_syntax("#{directory}/*", dir, type)
end
end
# Common method to test file syntax
def check_syntax(dirpath, dir = nil, type)
files = Dir.glob("#{dirpath}").select { |f| File.file?(f) }
files.each do |file|
fname = Pathname.new(file).basename
if ("#{fname}".end_with?('.json'))
ui.msg("Testing file #{file}")
json = File.new(file, 'r')
parser = Yajl::Parser.new
hash = parser.parse(json)
elsif("#{fname}".end_with?('.rb'))
ui.msg("Testing file #{file}")
system("ruby -c #{file}") or raise "Syntax check of #{file} failed!"
end
end
end
end
end