-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcli.py
More file actions
407 lines (353 loc) · 12.8 KB
/
cli.py
File metadata and controls
407 lines (353 loc) · 12.8 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
# Copyright (c) 2025, Salesforce, Inc.
# SPDX-License-Identifier: Apache-2
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from importlib import metadata
import json
import os
import sys
from typing import (
List,
Optional,
Union,
)
import click
from loguru import logger
from datacustomcode import AuthType
from datacustomcode.auth import configure_oauth_tokens
from datacustomcode.constants import (
CONFIG_FILE,
ENTRYPOINT_FILE,
PAYLOAD_DIR,
TEST_FILE,
TESTS_DIR,
)
from datacustomcode.scan import find_base_directory, get_package_type
@click.group()
@click.option("--debug", is_flag=True)
def cli(debug: bool):
logger.remove()
if debug:
logger.configure(handlers=[{"sink": sys.stderr, "level": "DEBUG"}])
else:
logger.configure(handlers=[{"sink": sys.stderr, "level": "INFO"}])
@cli.command()
def version():
"""Display the current version of the package."""
print(__name__)
try:
version = metadata.version("salesforce-data-customcode")
click.echo(f"salesforce-data-customcode version: {version}")
except metadata.PackageNotFoundError:
click.echo("Version information not available")
def _configure_client_credentials(
login_url: str,
client_id: str,
profile: str,
) -> None:
"""Configure credentials for Client Credentials authentication."""
from datacustomcode.credentials import AuthType, Credentials
client_secret = click.prompt("Client Secret")
credentials = Credentials(
login_url=login_url,
client_id=client_id,
auth_type=AuthType.CLIENT_CREDENTIALS,
client_secret=client_secret,
)
credentials.update_ini(profile=profile)
click.secho(
f"Client Credentials saved to profile '{profile}' successfully",
fg="green",
)
def _generate_function_test_file(entrypoint_path: str) -> Optional[str]:
"""Generate test.json file for a function.
Args:
entrypoint_path: Path to the function's entrypoint.py
Returns:
Path to generated test.json, or None if generation failed
"""
from datacustomcode.function_utils import generate_test_json
tests_dir = os.path.join(os.path.dirname(entrypoint_path), TESTS_DIR)
os.makedirs(tests_dir, exist_ok=True)
test_json_path = os.path.join(tests_dir, TEST_FILE)
try:
generate_test_json(entrypoint_path, test_json_path)
logger.debug(f"Generated test JSON at {test_json_path}")
return test_json_path
except Exception as e:
logger.warning(f"Could not generate test.json: {e}")
return None
@cli.command()
@click.option("--profile", default="default", help="Credential profile name")
@click.option(
"--auth-type",
type=click.Choice(["oauth_tokens", "client_credentials"]),
default="oauth_tokens",
help="""Authentication method to use.
\b
oauth_tokens - OAuth tokens (refresh_token) authentication (default)
client_credentials - Server-to-server using client_id/secret only
""",
)
def configure(profile: str, auth_type: str) -> None:
"""Configure credentials for connecting to Data Cloud."""
from datacustomcode.credentials import AuthType
# Common fields for all auth types
click.echo(f"\nConfiguring {auth_type} authentication for profile '{profile}':\n")
login_url = click.prompt("Login URL")
client_id = click.prompt("Client ID")
# Route to appropriate handler based on auth type
if auth_type == AuthType.OAUTH_TOKENS.value:
client_secret = click.prompt("Client Secret", hide_input=True)
redirect_uri = click.prompt("Redirect URI")
configure_oauth_tokens(
login_url, client_id, client_secret, redirect_uri, profile
)
elif auth_type == AuthType.CLIENT_CREDENTIALS.value:
_configure_client_credentials(login_url, client_id, profile)
@cli.command()
@click.option("--profile", default="default", help="Credential profile name")
def auth(profile: str):
from datacustomcode.credentials import Credentials
credentials = Credentials.from_available(profile=profile)
if not credentials.redirect_uri:
click.secho(
"Error: Redirect URI is required for OAuth Tokens authentication",
fg="red",
)
raise click.Abort()
if credentials.auth_type == AuthType.OAUTH_TOKENS:
configure_oauth_tokens(
login_url=credentials.login_url,
client_id=credentials.client_id,
client_secret=credentials.client_secret,
redirect_uri=credentials.redirect_uri,
profile=profile,
)
@cli.command()
@click.argument("path", default="payload")
@click.option("--network", default="default")
def zip(path: str, network: str):
from datacustomcode.deploy import zip
from datacustomcode.scan import find_base_directory, get_package_type
logger.debug("Zipping project")
base_directory = find_base_directory(path)
package_type = get_package_type(base_directory)
zip(path, network, package_type)
@cli.command()
@click.option("--path", default="payload")
@click.option("--name", required=True)
@click.option("--version", default="0.0.1")
@click.option("--description", default="Custom Data Transform Code")
@click.option("--profile", default="default")
@click.option("--network", default="default")
@click.option(
"--cpu-size",
default="CPU_2XL",
help="""CPU size for deployment. Available options:
\b
CPU_L - Large CPU instance
CPU_XL - X-Large CPU instance
CPU_2XL - 2X-Large CPU instance [DEFAULT]
CPU_4XL - 4X-Large CPU instance
Choose based on your workload requirements.""",
)
@click.option(
"--sf-cli-org",
default=None,
help="SF CLI org alias or username. Fetches credentials via `sf org display`.",
)
def deploy(
path: str,
name: str,
version: str,
description: str,
cpu_size: str,
profile: str,
network: str,
sf_cli_org: Optional[str],
):
from datacustomcode.constants import USE_IN_FEATURE_MAPPING_FOR_CONNECT_API
from datacustomcode.deploy import (
COMPUTE_TYPES,
CodeExtensionMetadata,
deploy_full,
infer_use_in_feature,
)
from datacustomcode.token_provider import (
CredentialsTokenProvider,
SFCLITokenProvider,
)
logger.debug("Deploying project")
if cpu_size not in COMPUTE_TYPES.keys():
click.secho(
f"Error: Invalid CPU size '{cpu_size}'. "
f"Available options: {', '.join(COMPUTE_TYPES.keys())}",
fg="red",
)
raise click.Abort()
logger.debug(f"Deploying with CPU size: {cpu_size}")
base_directory = find_base_directory(path)
package_type = get_package_type(base_directory)
metadata = CodeExtensionMetadata(
name=name,
version=version,
description=description,
computeType=COMPUTE_TYPES[cpu_size],
codeType=package_type,
)
if package_type == "function":
# Infer use_in_feature from function signature
entrypoint_path = os.path.join(path, ENTRYPOINT_FILE)
use_in_feature = infer_use_in_feature(entrypoint_path)
if use_in_feature:
logger.info(f"Inferred use_in_feature: {use_in_feature}")
else:
click.secho(
"Error: Could not infer function invoke options. "
"Please provide --use-in-feature",
fg="red",
)
raise click.Abort()
# Map user-provided feature names to API names
mapped_feature = USE_IN_FEATURE_MAPPING_FOR_CONNECT_API.get(
use_in_feature, use_in_feature
)
metadata.functionInvokeOptions = [mapped_feature]
try:
if sf_cli_org:
auth = SFCLITokenProvider(sf_cli_org).get_token()
else:
auth = CredentialsTokenProvider(profile).get_token()
except RuntimeError as e:
click.secho(f"Error: {e}", fg="red")
raise click.Abort() from None
deploy_full(path, metadata, auth, network)
@cli.command()
@click.argument("directory", default=".")
@click.option(
"--code-type", default="script", type=click.Choice(["script", "function"])
)
@click.option(
"--use-in-feature",
default="SearchIndexChunking",
help="Feature where this function will be used (only applicable for function).",
)
def init(directory: str, code_type: str, use_in_feature: Optional[str]):
from datacustomcode.scan import (
dc_config_json_from_file,
update_config,
write_sdk_config,
)
from datacustomcode.template import copy_function_template, copy_script_template
click.echo("Copying template to " + click.style(directory, fg="blue", bold=True))
if code_type == "script":
copy_script_template(directory)
elif code_type == "function":
copy_function_template(directory, use_in_feature)
entrypoint_path = os.path.join(directory, PAYLOAD_DIR, ENTRYPOINT_FILE)
config_location = os.path.join(os.path.dirname(entrypoint_path), CONFIG_FILE)
# Write package type to SDK-specific config
sdk_config = {"type": code_type}
write_sdk_config(directory, sdk_config)
config_json = dc_config_json_from_file(entrypoint_path, code_type)
with open(config_location, "w") as f:
json.dump(config_json, f, indent=2)
updated_config_json = update_config(entrypoint_path)
with open(config_location, "w") as f:
json.dump(updated_config_json, f, indent=2)
click.echo(
"Start developing by updating the code in "
+ click.style(entrypoint_path, fg="blue", bold=True)
)
click.echo(
"You can run "
+ click.style(f"datacustomcode scan {entrypoint_path}", fg="blue", bold=True)
+ " to automatically update config.json when you make changes to your code"
)
# Generate test.json for functions
if code_type == "function":
test_json_path = _generate_function_test_file(entrypoint_path)
if test_json_path:
click.echo(
"Generated test file at "
+ click.style(test_json_path, fg="blue", bold=True)
)
click.echo(
"Test your function locally with "
+ click.style(
f"datacustomcode run {entrypoint_path} "
f"--test-with {test_json_path}",
fg="blue",
bold=True,
)
)
@cli.command()
@click.argument("filename")
@click.option("--config")
@click.option("--dry-run", is_flag=True)
@click.option(
"--no-requirements", is_flag=True, help="Skip generating requirements.txt file"
)
def scan(filename: str, config: str, dry_run: bool, no_requirements: bool):
from datacustomcode.scan import update_config, write_requirements_file
config_location = config or os.path.join(os.path.dirname(filename), CONFIG_FILE)
click.echo(
"Dumping scan results to config file: "
+ click.style(config_location, fg="blue", bold=True)
)
click.echo("Scanning " + click.style(filename, fg="blue", bold=True) + "...")
config_json = update_config(filename)
click.secho(json.dumps(config_json, indent=2), fg="yellow")
if not dry_run:
with open(config_location, "w") as f:
json.dump(config_json, f, indent=2)
if not no_requirements:
requirements_path = write_requirements_file(filename)
click.echo(
"Generated requirements file: "
+ click.style(requirements_path, fg="blue", bold=True)
)
@cli.command()
@click.argument("entrypoint")
@click.option("--config-file", default=None)
@click.option("--dependencies", default=[], multiple=True)
@click.option("--profile", default="default")
@click.option(
"--test-with",
default=None,
type=click.Path(exists=True),
help="Path to test JSON file for function testing",
)
@click.option(
"--sf-cli-org",
default=None,
help="SF CLI org alias or username. Fetches credentials via `sf org display`.",
)
def run(
entrypoint: str,
config_file: Union[str, None],
dependencies: List[str],
profile: str,
test_with: Optional[str],
sf_cli_org: Optional[str],
):
from datacustomcode.run import run_entrypoint
run_entrypoint(
entrypoint,
config_file,
dependencies,
profile,
test_file=test_with,
sf_cli_org=sf_cli_org,
)