-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathpython.go
More file actions
424 lines (361 loc) · 14.8 KB
/
python.go
File metadata and controls
424 lines (361 loc) · 14.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// Copyright 2022-2026 Salesforce, Inc.
//
// 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.
package python
import (
"bytes"
"context"
_ "embed"
"fmt"
"path/filepath"
"regexp"
"runtime"
"strings"
"github.com/pelletier/go-toml/v2"
"github.com/slackapi/slack-cli/internal/hooks"
"github.com/slackapi/slack-cli/internal/iostreams"
"github.com/slackapi/slack-cli/internal/shared/types"
"github.com/slackapi/slack-cli/internal/style"
"github.com/spf13/afero"
)
//go:embed hooks.json
var hooksJSON []byte
// slackBoltPackageName is the name of the Bolt for Python dependency in requirements.txt
const slackBoltPackageName = "slack-bolt"
const (
// slackCLIHooksPackageName the name of the Python Hooks dependency in requirements.txt
slackCLIHooksPackageName = "slack-cli-hooks"
// slackCLIHooksPackageVersion is the version range of the Python Hooks dependency in requirements.txt
slackCLIHooksPackageVersion = "<1.0.0"
// slackCLIHooksPackageSpecifier is the package name and version range of the Python Hooks dependency in requirements.txt
slackCLIHooksPackageSpecifier = slackCLIHooksPackageName + slackCLIHooksPackageVersion
)
// Python runtime type
type Python struct {
}
// New creates a new Python runtime
func New() *Python {
return &Python{}
}
// IgnoreDirectories is a list of directories to ignore when packaging the runtime for deployment.
func (p *Python) IgnoreDirectories() []string {
return []string{}
}
// getVenvPath returns the path to the virtual environment directory
func getVenvPath(projectDirPath string) string {
return filepath.Join(projectDirPath, ".venv")
}
// getPythonExecutable returns the Python executable name for the current OS
func getPythonExecutable() string {
if runtime.GOOS == "windows" {
return "python"
}
return "python3"
}
// getPipExecutable returns the path to the pip executable in the virtual environment
func getPipExecutable(venvPath string) string {
if runtime.GOOS == "windows" {
return filepath.Join(venvPath, "Scripts", "pip.exe")
}
return filepath.Join(venvPath, "bin", "pip")
}
// venvExists checks if a virtual environment exists at the given path
func venvExists(fs afero.Fs, venvPath string) bool {
pipPath := getPipExecutable(venvPath)
if _, err := fs.Stat(pipPath); err == nil {
return true
}
return false
}
// createVirtualEnvironment creates a Python virtual environment
func createVirtualEnvironment(ctx context.Context, projectDirPath string, hookExecutor hooks.HookExecutor) error {
hookScript := hooks.HookScript{
Name: "CreateVirtualEnvironment",
Command: fmt.Sprintf("%s -m venv .venv", getPythonExecutable()),
}
stdout := bytes.Buffer{}
hookExecOpts := hooks.HookExecOpts{
Hook: hookScript,
Stdout: &stdout,
Directory: projectDirPath,
}
_, err := hookExecutor.Execute(ctx, hookExecOpts)
if err != nil {
return fmt.Errorf("failed to create virtual environment: %w\nOutput: %s", err, stdout.String())
}
return nil
}
// runPipInstall runs pip install with the given arguments.
// The venv does not need to be activated because pip is invoked by its full
// path inside the venv, which ensures packages are installed into the venv's
// site-packages directory.
func runPipInstall(ctx context.Context, venvPath string, projectDirPath string, hookExecutor hooks.HookExecutor, args ...string) (string, error) {
pipPath := getPipExecutable(venvPath)
cmdArgs := append([]string{pipPath, "install"}, args...)
hookScript := hooks.HookScript{
Name: "InstallProjectDependencies",
Command: strings.Join(cmdArgs, " "),
}
stdout := bytes.Buffer{}
hookExecOpts := hooks.HookExecOpts{
Hook: hookScript,
Stdout: &stdout,
Directory: projectDirPath,
}
_, err := hookExecutor.Execute(ctx, hookExecOpts)
output := stdout.String()
if err != nil {
return output, fmt.Errorf("pip install failed: %w", err)
}
return output, nil
}
// installRequirementsTxt handles adding slack-cli-hooks to requirements.txt
func installRequirementsTxt(fs afero.Fs, projectDirPath string) (output string, err error) {
requirementsFilePath := filepath.Join(projectDirPath, "requirements.txt")
file, err := afero.ReadFile(fs, requirementsFilePath)
if err != nil {
return fmt.Sprintf("Error reading requirements.txt: %s", err), err
}
fileData := string(file)
// Skip when slack-cli-hooks is already declared in requirements.txt
if strings.Contains(fileData, slackCLIHooksPackageName) {
return fmt.Sprintf("Found requirements.txt with %s", style.Highlight(slackCLIHooksPackageName)), nil
}
// Add slack-cli-hooks to requirements.txt
//
// Regex finds all lines that match "slack-bolt" including optional version specifier (e.g. slack-bolt==1.21.2)
re := regexp.MustCompile(fmt.Sprintf(`(%s.*)`, slackBoltPackageName))
matches := re.FindAllString(fileData, -1)
if len(matches) > 0 {
// Inserted under the slack-bolt dependency
fileData = re.ReplaceAllString(fileData, fmt.Sprintf("$1\n%s", slackCLIHooksPackageSpecifier))
} else {
// Insert at bottom of file
fileData = fmt.Sprintf("%s\n%s", strings.TrimSpace(fileData), slackCLIHooksPackageSpecifier)
}
// Save requirements.txt
err = afero.WriteFile(fs, requirementsFilePath, []byte(fileData), 0644)
if err != nil {
return fmt.Sprintf("Error updating requirements.txt: %s", err), err
}
return fmt.Sprintf("Updated requirements.txt with %s", style.Highlight(slackCLIHooksPackageSpecifier)), nil
}
// installPyProjectToml handles adding slack-cli-hooks to pyproject.toml
func installPyProjectToml(fs afero.Fs, projectDirPath string) (output string, err error) {
pyProjectFilePath := filepath.Join(projectDirPath, "pyproject.toml")
file, err := afero.ReadFile(fs, pyProjectFilePath)
if err != nil {
return fmt.Sprintf("Error reading pyproject.toml: %s", err), err
}
fileData := string(file)
// Check if slack-cli-hooks is already declared
if strings.Contains(fileData, slackCLIHooksPackageName) {
return fmt.Sprintf("Found pyproject.toml with %s", style.Highlight(slackCLIHooksPackageName)), nil
}
// Parse only to validate the file structure
var config map[string]interface{}
err = toml.Unmarshal(file, &config)
if err != nil {
return fmt.Sprintf("Error parsing pyproject.toml: %s", err), err
}
// Verify `project` section and `project.dependencies` array exist
projectSection, exists := config["project"]
if !exists {
err := fmt.Errorf("pyproject.toml missing project section")
return fmt.Sprintf("Error updating pyproject.toml: %s", err), err
}
projectMap, ok := projectSection.(map[string]interface{})
if !ok {
err := fmt.Errorf("pyproject.toml project section is not a valid format")
return fmt.Sprintf("Error updating pyproject.toml: %s", err), err
}
if _, exists := projectMap["dependencies"]; !exists {
err := fmt.Errorf("pyproject.toml missing dependencies array")
return fmt.Sprintf("Error updating pyproject.toml: %s", err), err
}
// Use string manipulation to add the dependency while preserving formatting.
// This regex matches the dependencies array and its contents, handling both single-line and multi-line formats.
// Note: This regex may not correctly handle commented-out dependencies arrays or nested brackets in string values.
// These edge cases are uncommon in practice and the TOML validation above will catch malformed files.
dependenciesRegex := regexp.MustCompile(`(?s)(dependencies\s*=\s*\[)([^\]]*?)(\])`)
matches := dependenciesRegex.FindStringSubmatch(fileData)
if len(matches) == 0 {
err := fmt.Errorf("pyproject.toml missing dependencies array")
return fmt.Sprintf("Error updating pyproject.toml: %s", err), err
}
prefix := matches[1] // "...dependencies = ["
content := matches[2] // array contents
suffix := matches[3] // "]..."
// Always append slack-cli-hooks at the end of the dependencies array.
// Formatting:
// - Multi-line arrays get a trailing comma to match Python/TOML conventions
// and make future additions cleaner.
// - Single-line arrays omit the trailing comma for a compact appearance,
// which is the typical style for short dependency lists.
var newContent string
content = strings.TrimRight(content, " \t\n")
if !strings.HasSuffix(content, ",") {
content += ","
}
if strings.Contains(content, "\n") {
// Multi-line format: append with proper indentation and trailing comma
newContent = content + "\n" + ` "` + slackCLIHooksPackageSpecifier + `",` + "\n"
} else {
// Single-line format: append inline without trailing comma
newContent = content + ` "` + slackCLIHooksPackageSpecifier + `"`
}
// Replace the dependencies array content
fileData = dependenciesRegex.ReplaceAllString(fileData, prefix+newContent+suffix)
// Save pyproject.toml
err = afero.WriteFile(fs, pyProjectFilePath, []byte(fileData), 0644)
if err != nil {
return fmt.Sprintf("Error updating pyproject.toml: %s", err), err
}
return fmt.Sprintf("Updated pyproject.toml with %s", style.Highlight(slackCLIHooksPackageSpecifier)), nil
}
// InstallProjectDependencies creates a virtual environment and installs project dependencies.
func (p *Python) InstallProjectDependencies(ctx context.Context, projectDirPath string, hookExecutor hooks.HookExecutor, ios iostreams.IOStreamer, fs afero.Fs, os types.Os) (output string, err error) {
var outputs []string
var errs []error
// Detect which dependency file(s) exist
requirementsFilePath := filepath.Join(projectDirPath, "requirements.txt")
pyProjectFilePath := filepath.Join(projectDirPath, "pyproject.toml")
hasRequirementsTxt := false
hasPyProjectToml := false
if _, err := fs.Stat(requirementsFilePath); err == nil {
hasRequirementsTxt = true
}
if _, err := fs.Stat(pyProjectFilePath); err == nil {
hasPyProjectToml = true
}
// Ensure at least one dependency file exists
if !hasRequirementsTxt && !hasPyProjectToml {
err := fmt.Errorf("no Python dependency file found (requirements.txt or pyproject.toml)")
return fmt.Sprintf("Error: %s", err), err
}
// Get virtual environment path
venvPath := getVenvPath(projectDirPath)
// Create virtual environment if it doesn't exist
if !venvExists(fs, venvPath) {
ios.PrintDebug(ctx, "Creating Python virtual environment")
if err := createVirtualEnvironment(ctx, projectDirPath, hookExecutor); err != nil {
outputs = append(outputs, fmt.Sprintf("Error creating virtual environment: %s", err))
return strings.Join(outputs, "\n"), err
}
outputs = append(outputs, fmt.Sprintf("Created virtual environment at %s", style.Highlight(".venv")))
} else {
outputs = append(outputs, fmt.Sprintf("Found existing virtual environment at %s", style.Highlight(".venv")))
}
// Handle requirements.txt if it exists
if hasRequirementsTxt {
output, err := installRequirementsTxt(fs, projectDirPath)
outputs = append(outputs, output)
if err != nil {
errs = append(errs, err)
}
}
// Handle pyproject.toml if it exists
if hasPyProjectToml {
output, err := installPyProjectToml(fs, projectDirPath)
outputs = append(outputs, output)
if err != nil {
errs = append(errs, err)
}
}
// Install dependencies using pip
// When both files exist, pyproject.toml is installed first to set up the project package
// and its declared dependencies. Then requirements.txt is installed second so its version
// pins take precedence, as it typically serves as the lockfile.
if hasPyProjectToml {
ios.PrintDebug(ctx, "Installing dependencies from pyproject.toml")
pipOutput, err := runPipInstall(ctx, venvPath, projectDirPath, hookExecutor, "-e", ".")
if err != nil {
errs = append(errs, err)
outputs = append(outputs, fmt.Sprintf("Error installing from pyproject.toml: %s\n%s", err, pipOutput))
} else {
outputs = append(outputs, fmt.Sprintf("Installed dependencies from %s", style.Highlight("pyproject.toml")))
}
}
if hasRequirementsTxt {
ios.PrintDebug(ctx, "Installing dependencies from requirements.txt")
pipOutput, err := runPipInstall(ctx, venvPath, projectDirPath, hookExecutor, "-r", "requirements.txt")
if err != nil {
errs = append(errs, err)
outputs = append(outputs, fmt.Sprintf("Error installing from requirements.txt: %s\n%s", err, pipOutput))
} else {
outputs = append(outputs, fmt.Sprintf("Installed dependencies from %s", style.Highlight("requirements.txt")))
}
}
// Return result
output = strings.Join(outputs, "\n")
if len(errs) > 0 {
return output, errs[0]
}
return output, nil
}
// Name prints the name of the runtime
func (p *Python) Name() string {
return "Python"
}
// Version is the runtime version used by the hosted app deployment
func (p *Python) Version() string {
return "python" // the server interprets this as: always the latest version layer
}
// SetVersion sets the Version value
func (p *Python) SetVersion(version string) {
// Unsupported
}
// HooksJSONTemplate returns the default hooks.json template
func (p *Python) HooksJSONTemplate() []byte {
return hooksJSON
}
// PreparePackage will prepare and copy the app in projectDirPath to tmpDirPath as a release-ready bundle.
func (p *Python) PreparePackage(ctx context.Context, sdkConfig hooks.SDKCLIConfig, hookExecutor hooks.HookExecutor, opts types.PreparePackageOpts) error {
return nil // Unsupported
}
// IsRuntimeForProject returns true if dirPath is a Python project
func IsRuntimeForProject(ctx context.Context, fs afero.Fs, dirPath string, sdkConfig hooks.SDKCLIConfig) bool {
// Is Python project when app manifest says so
if strings.HasPrefix(sdkConfig.Runtime, "python") {
return true
}
// Python projects must have a requirements.txt or pyproject.toml in the root dirPath
var requirementsTxtPath = filepath.Join(dirPath, "requirements.txt")
if _, err := fs.Stat(requirementsTxtPath); err == nil {
return true
}
var pyProjectTomlPath = filepath.Join(dirPath, "pyproject.toml")
if _, err := fs.Stat(pyProjectTomlPath); err == nil {
return true
}
return false
}
// getProjectDirRelPath returns the relative path from current working directory
// to projectDirPath or an error. When an error occurs, the projectDirPath is
// returned as the relative path.
func getProjectDirRelPath(os types.Os, currentDirPath string, projectDirPath string) (string, error) {
// Get the current directory to use as the base for the project
if currentDirPath == "" {
cwd, err := os.Getwd()
if err != nil {
return projectDirPath, err
}
currentDirPath = cwd
}
// Find relative path between current directory and project directory
filePathRel, err := filepath.Rel(currentDirPath, projectDirPath)
if err != nil {
return projectDirPath, err
}
return filePathRel, nil
}