-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathcli_pack.py
More file actions
620 lines (499 loc) · 20.6 KB
/
Copy pathcli_pack.py
File metadata and controls
620 lines (499 loc) · 20.6 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
# type: ignore
import json
import os
import re
import subprocess
import uuid
import zipfile
from string import Template
from typing import Dict, Tuple
import click
try:
import tomllib
except ImportError:
import tomli as tomllib
from ..telemetry import track
from ._utils._console import ConsoleLogger
console = ConsoleLogger()
schema = "https://cloud.uipath.com/draft/2024-12/entry-point"
def validate_config_structure(config_data):
required_fields = ["entryPoints"]
for field in required_fields:
if field not in config_data:
console.error(f"uipath.json is missing the required field: {field}.")
def check_config(directory):
config_path = os.path.join(directory, "uipath.json")
toml_path = os.path.join(directory, "pyproject.toml")
if not os.path.isfile(config_path):
console.error("uipath.json not found, please run `uipath init`.")
if not os.path.isfile(toml_path):
console.error("pyproject.toml not found.")
with open(config_path, "r") as config_file:
config_data = json.load(config_file)
validate_config_structure(config_data)
toml_data = read_toml_project(toml_path)
return {
"project_name": toml_data["name"],
"description": toml_data["description"],
"entryPoints": config_data["entryPoints"],
"version": toml_data["version"],
"authors": toml_data["authors"],
"dependencies": toml_data.get("dependencies", {}),
}
def is_uv_available():
"""Check if uv command is available in the system."""
try:
subprocess.run(["uv", "--version"], capture_output=True, check=True, timeout=20)
return True
except (subprocess.CalledProcessError, FileNotFoundError):
return False
except Exception as e:
console.warning(
f"An unexpected error occurred while checking uv availability: {str(e)}"
)
return False
def is_uv_project(directory):
"""Check if this is a uv project by looking for the uv.lock file."""
uv_lock_path = os.path.join(directory, "uv.lock")
# If uv.lock exists, it's definitely a uv project
if os.path.exists(uv_lock_path):
return True
return False
def run_uv_lock(directory):
"""Run uv lock to update the lock file."""
try:
subprocess.run(
["uv", "lock"],
cwd=directory,
capture_output=True,
text=True,
check=True,
timeout=60,
)
return True
except subprocess.CalledProcessError as e:
console.warning(f"uv lock failed: {e.stderr}")
return False
except FileNotFoundError:
console.warning("uv command not found. Skipping lock file update.")
return False
except Exception as e:
console.warning(f"An unexpected error occurred while running uv lock: {str(e)}")
return False
def handle_uv_operations(directory):
"""Handle uv operations if uv is detected and available."""
if not is_uv_available():
return
if not is_uv_project(directory):
return
# Always run uv lock to ensure lock file is up to date
run_uv_lock(directory)
def generate_operate_file(entryPoints, dependencies=None):
project_id = str(uuid.uuid4())
first_entry = entryPoints[0]
file_path = first_entry["filePath"]
type = first_entry["type"]
operate_json_data = {
"$schema": schema,
"projectId": project_id,
"main": file_path,
"contentType": type,
"targetFramework": "Portable",
"targetRuntime": "python",
"runtimeOptions": {"requiresUserInteraction": False, "isAttended": False},
}
# Add dependencies if provided
if dependencies:
operate_json_data["dependencies"] = dependencies
return operate_json_data
def generate_entrypoints_file(entryPoints):
entrypoint_json_data = {
"$schema": schema,
"$id": "entry-points.json",
"entryPoints": entryPoints,
}
return entrypoint_json_data
def generate_bindings_content():
bindings_content = {"version": "2.0", "resources": []}
return bindings_content
def generate_content_types_content():
templates_path = os.path.join(
os.path.dirname(__file__), "_templates", "[Content_Types].xml.template"
)
with open(templates_path, "r") as file:
content_types_content = file.read()
return content_types_content
def generate_nuspec_content(projectName, packageVersion, description, authors):
variables = {
"packageName": projectName,
"packageVersion": packageVersion,
"description": description,
"authors": authors,
}
templates_path = os.path.join(
os.path.dirname(__file__), "_templates", "package.nuspec.template"
)
with open(templates_path, "r", encoding="utf-8-sig") as f:
content = f.read()
return Template(content).substitute(variables)
def generate_rels_content(nuspecPath, psmdcpPath):
# /package/services/metadata/core-properties/254324ccede240e093a925f0231429a0.psmdcp
templates_path = os.path.join(
os.path.dirname(__file__), "_templates", ".rels.template"
)
nuspecId = "R" + str(uuid.uuid4()).replace("-", "")[:16]
psmdcpId = "R" + str(uuid.uuid4()).replace("-", "")[:16]
variables = {
"nuspecPath": nuspecPath,
"nuspecId": nuspecId,
"psmdcpPath": psmdcpPath,
"psmdcpId": psmdcpId,
}
with open(templates_path, "r", encoding="utf-8-sig") as f:
content = f.read()
return Template(content).substitute(variables)
def generate_psmdcp_content(projectName, version, description, authors):
templates_path = os.path.join(
os.path.dirname(__file__), "_templates", ".psmdcp.template"
)
token = str(uuid.uuid4()).replace("-", "")[:32]
random_file_name = f"{uuid.uuid4().hex[:16]}.psmdcp"
variables = {
"creator": authors,
"description": description,
"packageVersion": version,
"projectName": projectName,
"publicKeyToken": token,
}
with open(templates_path, "r", encoding="utf-8-sig") as f:
content = f.read()
return [random_file_name, Template(content).substitute(variables)]
def generate_package_descriptor_content(entryPoints):
files = {
"operate.json": "content/operate.json",
"entry-points.json": "content/entry-points.json",
"bindings.json": "content/bindings_v2.json",
}
for entry in entryPoints:
files[entry["filePath"]] = entry["filePath"]
package_descriptor_content = {
"$schema": "https://cloud.uipath.com/draft/2024-12/package-descriptor",
"files": files,
}
return package_descriptor_content
def is_venv_dir(d):
return (
os.path.exists(os.path.join(d, "Scripts", "activate"))
if os.name == "nt"
else os.path.exists(os.path.join(d, "bin", "activate"))
)
def pack_fn(
projectName,
description,
entryPoints,
version,
authors,
directory,
dependencies=None,
include_uv_lock=True,
):
operate_file = generate_operate_file(entryPoints, dependencies)
entrypoints_file = generate_entrypoints_file(entryPoints)
# Get bindings from uipath.json if available
config_path = os.path.join(directory, "uipath.json")
if not os.path.exists(config_path):
console.error("uipath.json not found, please run `uipath init`.")
# Define the allowlist of file extensions to include
file_extensions_included = [".py", ".mermaid", ".json", ".yaml", ".yml"]
files_included = []
# Binary files that should be read in binary mode
binary_extensions = [".exe", "", ".xlsx", ".xls"]
with open(config_path, "r") as f:
config_data = json.load(f)
if "bindings" in config_data:
bindings_content = config_data["bindings"]
else:
bindings_content = generate_bindings_content()
if "settings" in config_data:
settings = config_data["settings"]
if "fileExtensionsIncluded" in settings:
file_extensions_included.extend(settings["fileExtensionsIncluded"])
if "filesIncluded" in settings:
files_included = settings["filesIncluded"]
content_types_content = generate_content_types_content()
[psmdcp_file_name, psmdcp_content] = generate_psmdcp_content(
projectName, version, description, authors
)
nuspec_content = generate_nuspec_content(projectName, version, description, authors)
rels_content = generate_rels_content(
f"/{projectName}.nuspec",
f"/package/services/metadata/core-properties/{psmdcp_file_name}",
)
package_descriptor_content = generate_package_descriptor_content(entryPoints)
# Create .uipath directory if it doesn't exist
os.makedirs(".uipath", exist_ok=True)
with zipfile.ZipFile(
f".uipath/{projectName}.{version}.nupkg", "w", zipfile.ZIP_DEFLATED
) as z:
# Add metadata files
z.writestr(
f"./package/services/metadata/core-properties/{psmdcp_file_name}",
psmdcp_content,
)
z.writestr("[Content_Types].xml", content_types_content)
z.writestr(
"content/package-descriptor.json",
json.dumps(package_descriptor_content, indent=4),
)
z.writestr("content/operate.json", json.dumps(operate_file, indent=4))
z.writestr("content/entry-points.json", json.dumps(entrypoints_file, indent=4))
z.writestr("content/bindings_v2.json", json.dumps(bindings_content, indent=4))
z.writestr(f"{projectName}.nuspec", nuspec_content)
z.writestr("_rels/.rels", rels_content)
# Walk through directory and add all files with extensions in the allowlist
for root, dirs, files in os.walk(directory):
# Skip all directories that start with . or are a venv
dirs[:] = [
d
for d in dirs
if not d.startswith(".") and not is_venv_dir(os.path.join(root, d))
]
for file in files:
file_extension = os.path.splitext(file)[1].lower()
if file_extension in file_extensions_included or file in files_included:
file_path = os.path.join(root, file)
rel_path = os.path.relpath(file_path, directory)
if file_extension in binary_extensions:
# Read binary files in binary mode
with open(file_path, "rb") as f:
z.writestr(f"content/{rel_path}", f.read())
else:
try:
# Try UTF-8 first
with open(file_path, "r", encoding="utf-8") as f:
z.writestr(f"content/{rel_path}", f.read())
except UnicodeDecodeError:
# If UTF-8 fails, try with utf-8-sig (for files with BOM)
try:
with open(file_path, "r", encoding="utf-8-sig") as f:
z.writestr(f"content/{rel_path}", f.read())
except UnicodeDecodeError:
# If that also fails, try with latin-1 as a fallback
with open(file_path, "r", encoding="latin-1") as f:
z.writestr(f"content/{rel_path}", f.read())
# Handle optional files, conditionally including uv.lock
optional_files = ["pyproject.toml", "README.md"]
if include_uv_lock:
optional_files.append("uv.lock")
for file in optional_files:
file_path = os.path.join(directory, file)
if os.path.exists(file_path):
try:
with open(file_path, "r", encoding="utf-8") as f:
z.writestr(f"content/{file}", f.read())
except UnicodeDecodeError:
with open(file_path, "r", encoding="latin-1") as f:
z.writestr(f"content/{file}", f.read())
def parse_dependency_string(dependency: str) -> Tuple[str, str]:
"""Parse a dependency string into package name and version specifier.
Handles PEP 508 dependency specifications including:
- Simple names: "requests"
- Version specifiers: "requests>=2.28.0"
- Complex specifiers: "requests>=2.28.0,<3.0.0"
- Extras: "requests[security]>=2.28.0"
- Environment markers: "requests>=2.28.0; python_version>='3.8'"
Args:
dependency: Raw dependency string from pyproject.toml
Returns:
Tuple of (package_name, version_specifier)
Examples:
"requests" -> ("requests", "*")
"requests>=2.28.0" -> ("requests", ">=2.28.0")
"requests>=2.28.0,<3.0.0" -> ("requests", ">=2.28.0,<3.0.0")
"requests[security]>=2.28.0" -> ("requests", ">=2.28.0")
"""
# Remove whitespace
dependency = dependency.strip()
# Handle environment markers (everything after semicolon)
if ";" in dependency:
dependency = dependency.split(";")[0].strip()
# Pattern to match package name with optional extras and version specifiers
# Matches: package_name[extras] version_specs
pattern = r"^([a-zA-Z0-9]([a-zA-Z0-9._-]*[a-zA-Z0-9])?)(\[[^\]]+\])?(.*)"
match = re.match(pattern, dependency)
if not match:
# Fallback for edge cases
return dependency, "*"
package_name = match.group(1)
version_part = match.group(4).strip() if match.group(4) else ""
# If no version specifier, return wildcard
if not version_part:
return package_name, "*"
# Clean up version specifier
version_spec = version_part.strip()
# Validate that version specifier starts with a valid operator
valid_operators = [">=", "<=", "==", "!=", "~=", ">", "<"]
if not any(version_spec.startswith(op) for op in valid_operators):
# If it doesn't start with an operator, treat as exact version
if version_spec:
version_spec = f"=={version_spec}"
else:
version_spec = "*"
return package_name, version_spec
def extract_dependencies_from_toml(project_data: Dict) -> Dict[str, str]:
"""Extract and parse dependencies from pyproject.toml project data.
Args:
project_data: The "project" section from pyproject.toml
Returns:
Dictionary mapping package names to version specifiers
"""
dependencies = {}
if "dependencies" not in project_data:
return dependencies
deps_list = project_data["dependencies"]
if not isinstance(deps_list, list):
console.warning("dependencies should be a list in pyproject.toml")
return dependencies
for dep in deps_list:
if not isinstance(dep, str):
console.warning(f"Skipping non-string dependency: {dep}")
continue
try:
name, version_spec = parse_dependency_string(dep)
if name: # Only add if we got a valid name
dependencies[name] = version_spec
except Exception as e:
console.warning(f"Failed to parse dependency '{dep}': {e}")
continue
return dependencies
def read_toml_project(file_path: str) -> dict:
"""Read and parse pyproject.toml file with improved error handling and validation.
Args:
file_path: Path to pyproject.toml file
Returns:
Dictionary containing project metadata and dependencies
"""
try:
with open(file_path, "rb") as f:
content = tomllib.load(f)
except Exception as e:
console.error(f"Failed to read or parse pyproject.toml: {e}")
# Validate required sections
if "project" not in content:
console.error("pyproject.toml is missing the required field: project.")
project = content["project"]
# Validate required fields with better error messages
required_fields = {
"name": "Project name is required in pyproject.toml",
"description": "Project description is required in pyproject.toml",
"version": "Project version is required in pyproject.toml",
}
for field, error_msg in required_fields.items():
if field not in project:
console.error(
f"pyproject.toml is missing the required field: project.{field}. {error_msg}"
)
# Check for empty values only if field exists
if field in project and (
not project[field]
or (isinstance(project[field], str) and not project[field].strip())
):
console.error(
f"Project {field} cannot be empty. Please specify a {field} in pyproject.toml."
)
# Extract author information safely
authors = project.get("authors", [])
author_name = ""
if authors and isinstance(authors, list) and len(authors) > 0:
first_author = authors[0]
if isinstance(first_author, dict):
author_name = first_author.get("name", "")
elif isinstance(first_author, str):
# Handle case where authors is a list of strings
author_name = first_author
# Extract dependencies with improved parsing
dependencies = extract_dependencies_from_toml(project)
return {
"name": project["name"].strip(),
"description": project["description"].strip(),
"version": project["version"].strip(),
"authors": author_name.strip(),
"dependencies": dependencies,
}
def get_project_version(directory):
toml_path = os.path.join(directory, "pyproject.toml")
if not os.path.exists(toml_path):
console.warning("pyproject.toml not found. Using default version 0.0.1")
return "0.0.1"
toml_data = read_toml_project(toml_path)
return toml_data["version"]
def display_project_info(config):
max_label_length = max(
len(label) for label in ["Name", "Version", "Description", "Authors"]
)
max_length = 100
description = config["description"]
if len(description) >= max_length:
description = description[: max_length - 3] + " ..."
console.log(f"{'Name'.ljust(max_label_length)}: {config['project_name']}")
console.log(f"{'Version'.ljust(max_label_length)}: {config['version']}")
console.log(f"{'Description'.ljust(max_label_length)}: {description}")
console.log(f"{'Authors'.ljust(max_label_length)}: {config['authors']}")
@click.command()
@click.argument("root", type=str, default="./")
@click.option(
"--nolock",
is_flag=True,
help="Skip running uv lock and exclude uv.lock from the package",
)
@track
def pack(root, nolock):
"""Pack the project."""
version = get_project_version(root)
while not os.path.isfile(os.path.join(root, "uipath.json")):
console.error(
"uipath.json not found. Please run `uipath init` in the project directory."
)
config = check_config(root)
if not config["project_name"] or config["project_name"].strip() == "":
console.error(
"Project name cannot be empty. Please specify a name in pyproject.toml."
)
if not config["description"] or config["description"].strip() == "":
console.error(
"Project description cannot be empty. Please specify a description in pyproject.toml."
)
if not config["authors"] or config["authors"].strip() == "":
console.error(
'Project authors cannot be empty. Please specify authors in pyproject.toml:\n authors = [{ name = "John Doe" }]'
)
invalid_chars = ["&", "<", ">", '"', "'", ";"]
for char in invalid_chars:
if char in config["project_name"]:
console.error(f"Project name contains invalid character: '{char}'")
for char in invalid_chars:
if char in config["description"]:
console.error(f"Project description contains invalid character: '{char}'")
with console.spinner("Packaging project ..."):
try:
# Handle uv operations before packaging, unless nolock is specified
if not nolock:
handle_uv_operations(root)
pack_fn(
config["project_name"],
config["description"],
config["entryPoints"],
version or config["version"],
config["authors"],
root,
config.get("dependencies"),
include_uv_lock=not nolock,
)
display_project_info(config)
console.success("Project successfully packaged.")
except Exception as e:
console.error(
f"Failed to create package {config['project_name']}.{version or config['version']}: {str(e)}"
)
if __name__ == "__main__":
pack()