Debian Codegraph @

jenkins_jobs/cli/entry.py

raw
1 #!/usr/bin/env python
2 # Copyright (C) 2015 Wayne Warren
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import io
17 import os
18 import logging
19 import platform
20 from pathlib import Path
21
22 from stevedore import extension
23 import yaml
24
25 from jenkins_jobs.errors import JenkinsJobsException
26 from jenkins_jobs.cli.parser import create_parser
27 from jenkins_jobs.config import JJBConfig
28 from jenkins_jobs import utils
29 from jenkins_jobs import version
30
31 logging.basicConfig(level=logging.INFO)
32 logger = logging.getLogger()
33
34
35 def __version__():
36 return "Jenkins Job Builder version: %s" % version.version_info.version_string()
37
38
39 class JenkinsJobs(object):
40 """This is the entry point class for the `jenkins-jobs` command line tool.
41
42 While this class can be used programmatically by external users of the JJB
43 API, the main goal here is to abstract the `jenkins_jobs` tool in a way
44 that prevents test suites from caring overly much about various
45 implementation details--for example, tests of subcommands must not have
46 access to directly modify configuration objects, instead they must provide
47 a fixture in the form of an .ini file that provides the configuration
48 necessary for testing.
49
50 External users of the JJB API may be interested in this class as an
51 alternative to wrapping `jenkins_jobs` with a subprocess that execs it as a
52 system command; instead, python scripts may be written that pass
53 `jenkins_jobs` args directly to this class to allow programmatic setting of
54 various command line parameters.
55 """
56
57 def __init__(self, args=None, **kwargs):
58 if args is None:
59 args = []
60 self.parser = create_parser()
61 self.options = self.parser.parse_args(args)
62
63 self.jjb_config = JJBConfig(
64 self.options.conf, config_section=self.options.section, **kwargs
65 )
66
67 if not self.options.command:
68 self.parser.error("Must specify a 'command' to be performed")
69
70 if self.options.log_level is not None:
71 self.options.log_level = getattr(
72 logging, self.options.log_level.upper(), logger.getEffectiveLevel()
73 )
74 logger.setLevel(self.options.log_level)
75
76 self._parse_additional()
77 self.jjb_config.validate()
78
79 def _set_config(self, target, option):
80 """
81 Sets the option in target only if the given option was explicitly set
82 """
83 opt_val = getattr(self.options, option, None)
84 if opt_val is not None:
85 target[option] = opt_val
86
87 def _parse_additional(self):
88
89 self._set_config(self.jjb_config.builder, "ignore_cache")
90 self._set_config(self.jjb_config.builder, "flush_cache")
91 self._set_config(self.jjb_config.builder, "update")
92 self._set_config(self.jjb_config.yamlparser, "allow_empty_variables")
93 self._set_config(self.jjb_config.jenkins, "section")
94 self._set_config(self.jjb_config.jenkins, "user")
95 self._set_config(self.jjb_config.jenkins, "password")
96
97 # Note: CLI options override config file options.
98 if getattr(self.options, "update", None) is None:
99 self.options.update = self.jjb_config.builder.get("update")
100 if self.options.update is None:
101 self.options.update = "all"
102
103 if getattr(self.options, "plugins_info_path", None) is not None:
104 with io.open(
105 self.options.plugins_info_path, "r", encoding="utf-8"
106 ) as yaml_file:
107 plugins_info = yaml.safe_load(yaml_file)
108 if not isinstance(plugins_info, list):
109 self.parser.error(
110 "{0} must contain a Yaml list!".format(
111 self.options.plugins_info_path
112 )
113 )
114 self.jjb_config.builder["plugins_info"] = plugins_info
115
116 if getattr(self.options, "path", None):
117 if hasattr(self.options.path, "read"):
118 logger.debug("Input file is stdin")
119 if self.options.path.isatty():
120 if platform.system() == "Windows":
121 key = "CTRL+Z"
122 else:
123 key = "CTRL+D"
124 logger.warning(
125 "Reading configuration from STDIN. " "Press %s to end input.",
126 key,
127 )
128 self.options.path = [self.options.path]
129 else:
130 # take list of paths
131 self.options.path = [
132 Path(p) for p in self.options.path.split(os.pathsep)
133 ]
134
135 do_recurse = (
136 getattr(self.options, "recursive", False)
137 or self.jjb_config.recursive
138 )
139
140 excludes = [
141 e for elist in self.options.exclude for e in elist.split(os.pathsep)
142 ] or self.jjb_config.excludes
143 paths = []
144 for path in self.options.path:
145 if do_recurse and os.path.isdir(path):
146 paths.extend(utils.recurse_path(path, excludes))
147 else:
148 paths.append(path)
149 self.options.path = [Path(p) for p in paths]
150
151 def execute(self):
152
153 extension_manager = extension.ExtensionManager(
154 namespace="jjb.cli.subcommands", invoke_on_load=True
155 )
156
157 ext = extension_manager[self.options.command]
158 ext.obj.execute(self.options, self.jjb_config)
159
160
161 def main():
162
163 # utf-8 workaround for avoiding unicode errors in stdout/stderr
164 # see https://stackoverflow.com/a/2001767/99834
165 import sys
166
167 if sys.version_info[0] == 2:
168 import codecs
169
170 reload(sys) # noqa
171 sys.setdefaultencoding("utf-8")
172 sys.stdout = codecs.getwriter("utf8")(sys.stdout)
173 sys.stderr = codecs.getwriter("utf8")(sys.stderr)
174 # end of workaround
175
176 argv = sys.argv[1:]
177 jjb = JenkinsJobs(argv)
178 try:
179 jjb.execute()
180 except JenkinsJobsException as x:
181 print(file=sys.stderr)
182 for line in x.lines:
183 print(line, file=sys.stderr)
184 sys.exit(1)
185
186
187 if __name__ == "__main__":
188 main()