python-jcli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
jcli/plugins/node.py ADDED
@@ -0,0 +1,134 @@
1
+ """Jenkins Node management commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import click
6
+
7
+ from jcli.cli_helpers import get_client, get_formatter
8
+ from jcli.sdk.node import create_node, delete_node, get_node, list_nodes, toggle_offline
9
+
10
+
11
+ @click.group("node", help="Manage Jenkins nodes (agents).")
12
+ def node_group():
13
+ """Node management commands."""
14
+
15
+
16
+ @node_group.command("list")
17
+ @click.pass_context
18
+ def list_nodes_cmd(ctx: click.Context):
19
+ """List all Jenkins nodes."""
20
+ fmt = get_formatter(ctx)
21
+ client = get_client(ctx)
22
+
23
+ try:
24
+ nodes = list_nodes(client)
25
+ if nodes:
26
+ headers = ["Name", "Online", "Temporarily Offline", "Architecture"]
27
+ rows = [
28
+ [
29
+ n.get("displayName", "?"),
30
+ "Yes" if not n.get("offline", True) else "No",
31
+ "Yes" if n.get("temporarilyOffline", False) else "No",
32
+ n.get("monitorData", {}).get("hudson.node_monitors.ArchitectureMonitor", "?"),
33
+ ]
34
+ for n in nodes
35
+ ]
36
+ fmt.print_table(headers, rows, title="Jenkins Nodes")
37
+ else:
38
+ fmt.print_info("No nodes found.")
39
+ except Exception as exc:
40
+ fmt.print_error(str(exc))
41
+
42
+
43
+ @node_group.command("get")
44
+ @click.argument("name")
45
+ @click.pass_context
46
+ def get_node_cmd(ctx: click.Context, name: str):
47
+ """Get details of a specific node."""
48
+ fmt = get_formatter(ctx)
49
+ client = get_client(ctx)
50
+
51
+ try:
52
+ node = get_node(client, name)
53
+ if fmt.format_type == "json":
54
+ fmt.print_json(node)
55
+ else:
56
+ headers = ["Property", "Value"]
57
+ rows = [
58
+ ["Display Name", node.get("displayName", "?")],
59
+ ["Description", node.get("description", "") or "-"],
60
+ ["Offline", "Yes" if node.get("offline", True) else "No"],
61
+ ["Temporarily Offline", "Yes" if node.get("temporarilyOffline", False) else "No"],
62
+ ["Num Executors", str(node.get("numExecutors", "?"))],
63
+ ["Idle", "Yes" if node.get("idle", False) else "No"],
64
+ ["JNLP Agent", "Yes" if node.get("jnlpAgent", False) else "No"],
65
+ ]
66
+ # Add monitor data if available
67
+ monitor = node.get("monitorData", {})
68
+ if monitor:
69
+ for key, val in monitor.items():
70
+ if key.startswith("hudson.node_monitors."):
71
+ label = key.replace("hudson.node_monitors.", "")
72
+ rows.append([f"Monitor: {label}", str(val)])
73
+ fmt.print_table(headers, rows, title=f"Node: {name}")
74
+ except Exception as exc:
75
+ fmt.print_error(str(exc))
76
+
77
+
78
+ @node_group.command("delete")
79
+ @click.argument("name")
80
+ @click.option("--force", "-f", is_flag=True, help="Skip confirmation prompt.")
81
+ @click.pass_context
82
+ def delete_node_cmd(ctx: click.Context, name: str, force: bool):
83
+ """Delete a Jenkins node (agent)."""
84
+ fmt = get_formatter(ctx)
85
+ client = get_client(ctx)
86
+
87
+ if not force:
88
+ if not click.confirm(f"Are you sure you want to delete node '{name}'?"):
89
+ fmt.print_info("Delete cancelled.")
90
+ return
91
+
92
+ try:
93
+ delete_node(client, name)
94
+ fmt.print_success(f"Node '{name}' deleted successfully.")
95
+ except Exception as exc:
96
+ fmt.print_error(str(exc))
97
+
98
+
99
+ @node_group.command("toggle")
100
+ @click.argument("name")
101
+ @click.option("--message", "-m", default="", help="Reason for toggling offline/online.")
102
+ @click.pass_context
103
+ def toggle_node_cmd(ctx: click.Context, name: str, message: str):
104
+ """Toggle a node offline or online."""
105
+ fmt = get_formatter(ctx)
106
+ client = get_client(ctx)
107
+
108
+ try:
109
+ toggle_offline(client, name, msg=message)
110
+ fmt.print_success(f"Node '{name}' toggled successfully.")
111
+ except Exception as exc:
112
+ fmt.print_error(str(exc))
113
+
114
+
115
+ @node_group.command("create")
116
+ @click.argument("name")
117
+ @click.option("--executors", type=int, default=1, help="Number of executors (default: 1).")
118
+ @click.option("--remote-fs", default="/tmp", help="Remote filesystem root (default: /tmp).")
119
+ @click.option("--labels", default="", help="Node labels.")
120
+ @click.pass_context
121
+ def create_node_cmd(ctx: click.Context, name: str, executors: int, remote_fs: str, labels: str):
122
+ """Create a new Jenkins agent node."""
123
+ client = get_client(ctx)
124
+ fmt = get_formatter(ctx)
125
+ try:
126
+ create_node(client, name, num_executors=executors, remote_fs=remote_fs, labels=labels)
127
+ fmt.print_success(f"Node '{name}' created.")
128
+ except Exception as exc:
129
+ fmt.print_error(str(exc))
130
+
131
+
132
+ def register(parent_group):
133
+ """Register the node subgroup under the parent Click group."""
134
+ parent_group.add_command(node_group)
@@ -0,0 +1,108 @@
1
+ """Jenkins Pipeline management commands."""
2
+
3
+ import click
4
+
5
+ from jcli.cli_helpers import get_client, get_formatter
6
+ from jcli.sdk.exceptions import (
7
+ JenkinsAPIError,
8
+ JenkinsAuthError,
9
+ JenkinsConnectionError,
10
+ JenkinsNotFoundError,
11
+ )
12
+ from jcli.sdk.pipeline import (
13
+ get_pending_input,
14
+ get_pipeline_log,
15
+ get_pipeline_stages,
16
+ validate_jenkinsfile,
17
+ )
18
+
19
+
20
+ @click.group("pipeline", help="Manage Jenkins pipelines.")
21
+ def pipeline_group():
22
+ """Pipeline management commands."""
23
+
24
+
25
+ @pipeline_group.command("stages")
26
+ @click.argument("job_name")
27
+ @click.argument("build_number")
28
+ @click.pass_context
29
+ def stages(ctx, job_name, build_number):
30
+ """List stages for a Pipeline build.
31
+
32
+ JOB_NAME is the Pipeline job name.
33
+ BUILD_NUMBER is the build number to query.
34
+ """
35
+ client = get_client(ctx)
36
+ fmt = get_formatter(ctx)
37
+
38
+ try:
39
+ result = get_pipeline_stages(client, job_name, build_number)
40
+ fmt.print_json(result)
41
+ except (JenkinsNotFoundError, JenkinsAuthError, JenkinsConnectionError, JenkinsAPIError) as exc:
42
+ fmt.print_error(str(exc))
43
+
44
+
45
+ @pipeline_group.command("log")
46
+ @click.argument("job_name")
47
+ @click.argument("build_number")
48
+ @click.argument("node_id")
49
+ @click.pass_context
50
+ def log(ctx, job_name, build_number, node_id):
51
+ """Get log output for a Pipeline step.
52
+
53
+ JOB_NAME is the Pipeline job name.
54
+ BUILD_NUMBER is the build number to query.
55
+ NODE_ID is the flow node ID from stage/step info.
56
+ """
57
+ client = get_client(ctx)
58
+ fmt = get_formatter(ctx)
59
+
60
+ try:
61
+ result = get_pipeline_log(client, job_name, build_number, node_id)
62
+ fmt.print_json(result)
63
+ except (JenkinsNotFoundError, JenkinsAuthError, JenkinsConnectionError, JenkinsAPIError) as exc:
64
+ fmt.print_error(str(exc))
65
+
66
+
67
+ @pipeline_group.command("validate")
68
+ @click.argument("file_path", type=click.Path(exists=True, dir_okay=False))
69
+ @click.pass_context
70
+ def validate(ctx, file_path):
71
+ """Validate a Jenkinsfile against the Jenkins server.
72
+
73
+ FILE_PATH is the path to the Jenkinsfile to validate.
74
+ """
75
+ with open(file_path, "r", encoding="utf-8") as f:
76
+ content = f.read()
77
+
78
+ client = get_client(ctx)
79
+ fmt = get_formatter(ctx)
80
+
81
+ result = validate_jenkinsfile(client, content)
82
+
83
+ fmt.print_json(result)
84
+
85
+
86
+ @pipeline_group.command("pending")
87
+ @click.argument("job_name")
88
+ @click.argument("build_number")
89
+ @click.pass_context
90
+ def pending(ctx, job_name, build_number):
91
+ """Show pending input actions for a Pipeline build.
92
+
93
+ JOB_NAME is the Pipeline job name.
94
+ BUILD_NUMBER is the build number to query.
95
+ """
96
+ client = get_client(ctx)
97
+ fmt = get_formatter(ctx)
98
+
99
+ try:
100
+ result = get_pending_input(client, job_name, build_number)
101
+ fmt.print_json(result)
102
+ except (JenkinsNotFoundError, JenkinsAuthError, JenkinsConnectionError, JenkinsAPIError) as exc:
103
+ fmt.print_error(str(exc))
104
+
105
+
106
+ def register(parent_group):
107
+ """Register the pipeline subgroup under the parent Click group."""
108
+ parent_group.add_command(pipeline_group)
jcli/plugins/plugin.py ADDED
@@ -0,0 +1,173 @@
1
+ """Jenkins Plugin management commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import click
6
+
7
+ from jcli.cli_helpers import get_client, get_formatter
8
+ from jcli.sdk.plugin import (
9
+ check_plugin_updates,
10
+ get_plugin,
11
+ install_plugins,
12
+ list_plugins,
13
+ uninstall_plugin,
14
+ )
15
+
16
+
17
+ def _parse_plugin_spec(spec: str) -> tuple[str, str | None]:
18
+ """Parse a plugin spec like 'git' or 'git@5.0.0'.
19
+
20
+ Returns:
21
+ (short_name, version_or_None)
22
+ """
23
+ if "@" in spec:
24
+ name, _, version = spec.partition("@")
25
+ return name, version
26
+ return spec, None
27
+
28
+
29
+ # ------------------------------------------------------------------
30
+ # Plugin command group
31
+ # ------------------------------------------------------------------
32
+
33
+
34
+ @click.group("plugin", help="Manage Jenkins plugins.")
35
+ @click.pass_context
36
+ def plugin_group(ctx):
37
+ """Plugin management commands."""
38
+
39
+
40
+ @plugin_group.command("list")
41
+ @click.pass_context
42
+ def list_cmd(ctx):
43
+ """List installed Jenkins plugins."""
44
+ client = get_client(ctx)
45
+ fmt = get_formatter(ctx)
46
+
47
+ try:
48
+ plugins = list_plugins(client)
49
+ except Exception as exc:
50
+ fmt.print_error(str(exc))
51
+ raise SystemExit(1)
52
+
53
+ if not plugins:
54
+ fmt.print_info("No plugins found.")
55
+ return
56
+
57
+ headers = ["Name", "Version", "Active", "Update"]
58
+ rows = [
59
+ [p.get("shortName", "?"), p.get("version", "?"),
60
+ "Yes" if p.get("active") else "No",
61
+ "Yes" if p.get("hasUpdate") else "No"]
62
+ for p in plugins
63
+ ]
64
+ fmt.print_table(headers, rows, title="Installed Plugins")
65
+
66
+
67
+ @plugin_group.command("get")
68
+ @click.argument("name")
69
+ @click.pass_context
70
+ def get_cmd(ctx, name):
71
+ """Show details for a single plugin."""
72
+ client = get_client(ctx)
73
+ fmt = get_formatter(ctx)
74
+
75
+ try:
76
+ plugin = get_plugin(client, name)
77
+ except Exception as exc:
78
+ fmt.print_error(str(exc))
79
+ raise SystemExit(1)
80
+
81
+ # Display all fields in a vertical key-value table
82
+ headers = ["Field", "Value"]
83
+ rows = [[str(k), str(v)] for k, v in plugin.items()] if plugin else []
84
+ fmt.print_table(
85
+ headers,
86
+ rows,
87
+ title=f"Plugin: {plugin.get('shortName', name)}" if plugin else f"Plugin {name}",
88
+ )
89
+
90
+
91
+ @plugin_group.command("install")
92
+ @click.argument("plugin_spec")
93
+ @click.pass_context
94
+ def install_cmd(ctx, plugin_spec):
95
+ """Install a Jenkins plugin.
96
+
97
+ PLUGIN_SPEC can be just a plugin name (e.g. 'git') or
98
+ name@version (e.g. 'git@5.0.0') to install a specific version.
99
+ """
100
+ client = get_client(ctx)
101
+ fmt = get_formatter(ctx)
102
+
103
+ name, version = _parse_plugin_spec(plugin_spec)
104
+ plugins_dict: dict[str, str | None] = {name: version}
105
+
106
+ try:
107
+ install_plugins(client, plugins_dict)
108
+ except Exception as exc:
109
+ fmt.print_error(str(exc))
110
+ raise SystemExit(1)
111
+
112
+ msg = f"Plugin '{name}' installed successfully"
113
+ if version:
114
+ msg += f" (version {version})"
115
+ fmt.print_success(msg)
116
+
117
+
118
+ @plugin_group.command("uninstall")
119
+ @click.argument("name")
120
+ @click.pass_context
121
+ def uninstall_cmd(ctx, name):
122
+ """Uninstall a Jenkins plugin.
123
+
124
+ The plugin is scheduled for removal; a server restart is typically
125
+ required to complete the uninstall.
126
+ """
127
+ client = get_client(ctx)
128
+ fmt = get_formatter(ctx)
129
+
130
+ try:
131
+ uninstall_plugin(client, name)
132
+ except Exception as exc:
133
+ fmt.print_error(str(exc))
134
+ raise SystemExit(1)
135
+
136
+ fmt.print_success(f"Plugin '{name}' scheduled for uninstall (restart may be required)")
137
+
138
+
139
+ @plugin_group.command("check-updates")
140
+ @click.pass_context
141
+ def check_updates_cmd(ctx):
142
+ """Check for available plugin updates."""
143
+ client = get_client(ctx)
144
+ fmt = get_formatter(ctx)
145
+ try:
146
+ result = check_plugin_updates(client)
147
+ fmt.print_info("Plugin update check triggered. Run 'jcli plugin list' to see results.")
148
+ if isinstance(result, dict) and result:
149
+ fmt.print_json(result)
150
+ except Exception as exc:
151
+ fmt.print_error(str(exc))
152
+
153
+
154
+ @plugin_group.command("restart")
155
+ @click.option("--yes", "-y", is_flag=True, help="Skip confirmation prompt.")
156
+ @click.pass_context
157
+ def restart_cmd(ctx, yes):
158
+ """Restart Jenkins after plugin changes."""
159
+ if not yes:
160
+ click.confirm("Restart Jenkins server?", abort=True)
161
+ client = get_client(ctx)
162
+ fmt = get_formatter(ctx)
163
+ try:
164
+ from jcli.sdk.system import safe_restart
165
+ safe_restart(client)
166
+ fmt.print_success("Jenkins restart initiated.")
167
+ except Exception as exc:
168
+ fmt.print_error(str(exc))
169
+
170
+
171
+ def register(parent_group):
172
+ """Register the plugin subgroup under the parent Click group."""
173
+ parent_group.add_command(plugin_group)