forked from UiPath/uipath-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli_invoke.py
More file actions
126 lines (106 loc) · 4.23 KB
/
Copy pathcli_invoke.py
File metadata and controls
126 lines (106 loc) · 4.23 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import asyncio
import logging
import os
import tomllib
import click
import httpx
from .._utils._ssl_context import get_httpx_client_kwargs
from ._telemetry import track_command
from ._utils._common import get_env_vars
from ._utils._console import ConsoleLogger
from ._utils._folders import get_personal_workspace_info_async
from ._utils._processes import get_release_info
from .middlewares import Middlewares
logger = logging.getLogger(__name__)
console = ConsoleLogger()
def _read_project_details() -> tuple[str, str]:
current_path = os.getcwd()
toml_path = os.path.join(current_path, "pyproject.toml")
if not os.path.isfile(toml_path):
console.error("pyproject.toml not found.")
with open(toml_path, "rb") as f:
content = tomllib.load(f)
if "project" not in content:
console.error("pyproject.toml is missing the required field: project.")
if "name" not in content["project"]:
console.error("pyproject.toml is missing the required field: project.name.")
return content["project"]["name"], content["project"]["version"]
@click.command()
@click.argument("entrypoint", required=False)
@click.argument("input", required=False, default="{}")
@click.option(
"-f",
"--file",
required=False,
type=click.Path(exists=True),
help="File path for the .json input",
)
@track_command("invoke")
def invoke(entrypoint: str | None, input: str | None, file: str | None) -> None:
"""Invoke an agent published in my workspace."""
if file:
_, file_extension = os.path.splitext(file)
if file_extension != ".json":
console.error("Input file extension must be '.json'.")
with open(file) as f:
input = f.read()
with console.spinner("Loading configuration ..."):
[base_url, token] = get_env_vars()
url = f"{base_url}/orchestrator_/odata/Jobs/UiPath.Server.Configuration.OData.StartJobs"
_, personal_workspace_folder_id = asyncio.run(
get_personal_workspace_info_async()
)
project_name, project_version = _read_project_details()
if not personal_workspace_folder_id:
console.error(
"No personal workspace found for user. Please try reauthenticating."
)
return
_, release_key = get_release_info(
base_url, token, project_name, project_version, personal_workspace_folder_id
)
payload = {
"StartInfo": {
"ReleaseKey": str(release_key),
"RunAsMe": True,
"InputArguments": input,
"EntryPointPath": entrypoint,
}
}
headers = {
"Authorization": f"Bearer {token}",
"x-uipath-organizationunitid": str(personal_workspace_folder_id),
}
context = {
"url": url,
"payload": payload,
"headers": headers,
}
result = Middlewares.next("invoke", context)
if result.error_message:
console.error(
result.error_message, include_traceback=result.should_include_stacktrace
)
if result.info_message:
console.info(result.info_message)
if not result.should_continue:
return
with httpx.Client(**get_httpx_client_kwargs()) as client:
response = client.post(url, json=payload, headers=headers)
if response.status_code == 201:
job_key = None
try:
job_key = response.json()["value"][0]["Key"]
except KeyError:
console.error("Error: Failed to get job key from response")
if job_key:
with console.spinner("Starting job ..."):
job_url = f"{base_url}/orchestrator_/jobs(sidepanel:sidepanel/jobs/{job_key}/details)?fid={personal_workspace_folder_id}"
console.magic("Job started successfully!")
console.link("Monitor your job here: ", job_url)
else:
console.error(
f"Error: Failed to start job. Status code: {response.status_code} {response.text}"
)
if __name__ == "__main__":
invoke()