Python: introduce PyExecResult as an alias for Result<T, ExecError>.

It is just more convenient to right less generic params.

GitOrigin-RevId: cd33be23da4bb3cb09658aa6564e4d298a3ba72d
This commit is contained in:
Ilya.Kazakevich
2025-05-14 20:47:57 +00:00
committed by intellij-monorepo-bot
parent f1f77c0af7
commit 6bf17f551a
22 changed files with 109 additions and 116 deletions
@@ -6,6 +6,7 @@ import com.jetbrains.python.packaging.PyExecutionException
/**
* This class is expected to be used as a return value of most PyCharm APIs.
* Use it instead of exceptions and Kotlin Result.
* If your function returns [ExecError] only, use [PyExecResult]
*/
typealias PyResult<T> = com.jetbrains.python.Result<T, PyError>
/**
@@ -10,6 +10,7 @@ import com.intellij.python.community.execService.impl.ExecServiceImpl
import com.jetbrains.python.PythonBinary
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.ExecError
import com.jetbrains.python.errorProcessing.PyExecResult
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.CheckReturnValue
import org.jetbrains.annotations.Nls
@@ -49,7 +50,7 @@ interface ExecService {
args: List<String> = emptyList(),
options: ExecOptions = ExecOptions(),
processInteractiveHandler: ProcessInteractiveHandler<T>,
): Result<T, ExecError>
): PyExecResult<T>
/**
* Execute [whatToExec] with [args] and get both stdout/stderr outputs if `errorCode != 0`, returns error otherwise.
@@ -66,7 +67,7 @@ interface ExecService {
options: ExecOptions = ExecOptions(),
procListener: PyProcessListener? = null,
processOutputTransformer: ProcessOutputTransformer<T>,
): Result<T, ExecError>
): PyExecResult<T>
/**
* See [execute]
@@ -77,7 +78,7 @@ interface ExecService {
args: List<String> = emptyList(),
options: ExecOptions = ExecOptions(),
procListener: PyProcessListener? = null,
): Result<String, ExecError> = execute(
): PyExecResult<String> = execute(
whatToExec = whatToExec,
args = args,
options = options,
@@ -2,10 +2,8 @@
package com.intellij.python.community.execService.impl
import com.intellij.openapi.diagnostic.fileLogger
import com.intellij.platform.eel.EelExecApi
import com.intellij.platform.eel.EelProcess
import com.intellij.platform.eel.ExecuteProcessException
import com.intellij.platform.eel.getOr
import com.intellij.platform.eel.path.EelPath
import com.intellij.platform.eel.provider.asEelPath
import com.intellij.platform.eel.provider.getEelDescriptor
@@ -16,6 +14,7 @@ import com.jetbrains.python.PythonHelpersLocator
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.ExecError
import com.jetbrains.python.errorProcessing.ExecErrorReason
import com.jetbrains.python.errorProcessing.PyExecResult
import com.jetbrains.python.errorProcessing.failure
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.withTimeout
@@ -31,7 +30,7 @@ internal object ExecServiceImpl : ExecService {
args: List<String>,
options: ExecOptions,
processInteractiveHandler: ProcessInteractiveHandler<T>,
): Result<T, ExecError> {
): PyExecResult<T> {
val executableProcess = whatToExec.buildExecutableProcess(args, options)
val eelProcess = executableProcess.run().getOr { return it }
@@ -59,7 +58,7 @@ internal object ExecServiceImpl : ExecService {
options: ExecOptions,
procListener: PyProcessListener?,
processOutputTransformer: ProcessOutputTransformer<T>,
): Result<T, ExecError> {
): PyExecResult<T> {
val executableProcess = whatToExec.buildExecutableProcess(args, options)
val eelProcess = executableProcess.run().getOr { return it }
@@ -112,7 +111,7 @@ private suspend fun WhatToExec.buildExecutableProcess(args: List<String>, option
}
@CheckReturnValue
private suspend fun EelExecutableProcess.run(): Result<EelProcess, ExecError> {
private suspend fun EelExecutableProcess.run(): PyExecResult<EelProcess> {
val workingDirectory = if (workingDirectory != null && !workingDirectory.isAbsolute) workingDirectory.toRealPath() else workingDirectory
try {
val executionResult = exe.descriptor.upgrade().exec.spawnProcess(exe.toString())
@@ -12,7 +12,7 @@ import com.intellij.python.hatch.PyHatchBundle
import com.intellij.python.hatch.runtime.HatchConstants
import com.intellij.python.hatch.runtime.HatchRuntime
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.ExecError
import com.jetbrains.python.errorProcessing.PyExecResult
import com.jetbrains.python.errorProcessing.PyResult
import io.github.z4kn4fein.semver.Version
import io.github.z4kn4fein.semver.VersionFormatException
@@ -21,7 +21,7 @@ import java.nio.file.Path
/**
* Handles hatch-specific errors, runs [transformer] only on outputs with codes 0 or 1 without tracebacks.
*/
private suspend fun <T> HatchRuntime.executeAndHandleErrors(vararg arguments: String, transformer: ProcessOutputTransformer<T>): Result<T, ExecError> {
private suspend fun <T> HatchRuntime.executeAndHandleErrors(vararg arguments: String, transformer: ProcessOutputTransformer<T>): PyExecResult<T> {
val errorHandlerTransformer: ProcessOutputTransformer<T> = { output ->
when {
output.exitCode !in 0..1 -> Result.failure(null)
@@ -41,7 +41,7 @@ private suspend fun <T> HatchRuntime.executeAndMatch(
expectedOutput: Regex,
outputContentSupplier: (EelProcessExecutionResultInfo) -> String = { it.stdoutString },
transformer: (MatchResult) -> Result<T, @NlsSafe String?>,
): Result<T, ExecError> {
): PyExecResult<T> {
return this.executeAndHandleErrors(*arguments) { processOutput ->
if (processOutput.exitCode != 0) return@executeAndHandleErrors Result.failure(null)
@@ -60,11 +60,11 @@ sealed class HatchCommand(private val command: Array<String>, protected val runt
@Suppress("unused")
constructor(command: String, runtime: HatchRuntime) : this(arrayOf(command), runtime)
protected suspend fun <T> executeAndHandleErrors(vararg arguments: String, transformer: ProcessOutputTransformer<T>): Result<T, ExecError> {
protected suspend fun <T> executeAndHandleErrors(vararg arguments: String, transformer: ProcessOutputTransformer<T>): PyExecResult<T> {
return runtime.executeAndHandleErrors(*command, *arguments, transformer = transformer)
}
protected suspend fun <T> executeAndMatch(vararg arguments: String, expectedOutput: Regex, transformer: (MatchResult) -> Result<T, @NlsSafe String?>): Result<T, ExecError> {
protected suspend fun <T> executeAndMatch(vararg arguments: String, expectedOutput: Regex, transformer: (MatchResult) -> Result<T, @NlsSafe String?>): PyExecResult<T> {
return runtime.executeAndMatch(*command, *arguments, expectedOutput = expectedOutput, transformer = transformer)
}
}
@@ -73,12 +73,12 @@ class HatchCli(private val runtime: HatchRuntime) {
/**
* Build a project
*/
fun build(): Result<Unit, ExecError> = TODO()
fun build(): PyExecResult<Unit> = TODO()
/**
* Remove build artifacts
*/
fun clean(): Result<Unit, ExecError> = TODO()
fun clean(): PyExecResult<Unit> = TODO()
/**
* Manage the config file
@@ -98,7 +98,7 @@ class HatchCli(private val runtime: HatchRuntime) {
/**
* Format and lint source code
*/
fun fmt(): Result<Unit, ExecError> = TODO()
fun fmt(): PyExecResult<Unit> = TODO()
/**
* Create or initialize a project.
@@ -139,7 +139,7 @@ class HatchCli(private val runtime: HatchRuntime) {
/**
* Publish build artifacts
*/
fun publish(): Result<Unit, ExecError> = TODO()
fun publish(): PyExecResult<Unit> = TODO()
/**
* Manage Python installations
@@ -149,7 +149,7 @@ class HatchCli(private val runtime: HatchRuntime) {
/**
* Run commands within project environments
*/
suspend fun run(envName: String? = null, vararg command: String): Result<String, ExecError> {
suspend fun run(envName: String? = null, vararg command: String): PyExecResult<String> {
val envRuntime = envName?.let { runtime.withEnv(HatchConstants.AppEnvVars.ENV to it) } ?: runtime
return envRuntime.executeAndHandleErrors("run", *command) { output ->
if (output.exitCode != 0) return@executeAndHandleErrors Result.failure(null)
@@ -170,14 +170,14 @@ class HatchCli(private val runtime: HatchRuntime) {
/**
* Enter a shell within a project's environment
*/
fun shell(): Result<Unit, ExecError> = TODO()
fun shell(): PyExecResult<Unit> = TODO()
data class HatchStatus(val project: String, val location: Path, val config: Path)
/**
* Show information about the current environment
*/
suspend fun status(): Result<HatchStatus, ExecError> {
suspend fun status(): PyExecResult<HatchStatus> {
val expectedOutput = """^\[Project] - (.*)\n\[Location] - (.*)\n\[Config] - (.*)\n$""".toRegex()
return runtime.executeAndMatch("status", expectedOutput = expectedOutput, outputContentSupplier = { it.stderrString }) { matchResult ->
@@ -194,14 +194,14 @@ class HatchCli(private val runtime: HatchRuntime) {
/**
* Run tests
*/
fun test(): Result<Unit, ExecError> = TODO()
fun test(): PyExecResult<Unit> = TODO()
/**
* View a project's version.
*
* @return Project Version
*/
suspend fun getVersion(): Result<Version, ExecError> {
suspend fun getVersion(): PyExecResult<Version> {
return runtime.executeAndHandleErrors("version") { processOutput ->
val output = processOutput.takeIf { it.exitCode == 0 }?.stdoutString?.trim()
?: return@executeAndHandleErrors Result.failure(null)
@@ -3,8 +3,7 @@ package com.intellij.python.hatch.cli
import com.intellij.python.community.execService.ZeroCodeStdoutTransformer
import com.intellij.python.hatch.runtime.HatchRuntime
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.ExecError
import com.jetbrains.python.errorProcessing.PyExecResult
/**
* Manage environment dependencies
@@ -13,28 +12,28 @@ class HatchConfig(runtime: HatchRuntime) : HatchCommand("config", runtime) {
/**
* Open the config location in your file manager
*/
suspend fun explore(): Result<String, ExecError> {
suspend fun explore(): PyExecResult<String> {
return executeAndHandleErrors("explore", transformer = ZeroCodeStdoutTransformer)
}
/**
* Show the location of the config file
*/
suspend fun find(): Result<String, ExecError> {
suspend fun find(): PyExecResult<String> {
return executeAndHandleErrors("find", transformer = ZeroCodeStdoutTransformer)
}
/**
* Restore the config file to default settings
*/
suspend fun restore(): Result<String, ExecError> {
suspend fun restore(): PyExecResult<String> {
return executeAndHandleErrors("restore", transformer = ZeroCodeStdoutTransformer)
}
/**
* Assign values to config file entries
*/
suspend fun set(key: String, value: String): Result<String, ExecError> {
suspend fun set(key: String, value: String): PyExecResult<String> {
return executeAndHandleErrors("set", key, value, transformer = ZeroCodeStdoutTransformer)
}
@@ -43,7 +42,7 @@ class HatchConfig(runtime: HatchRuntime) : HatchCommand("config", runtime) {
*
* @param all Do not scrub secret fields
*/
suspend fun show(all: Boolean? = null): Result<String, ExecError> {
suspend fun show(all: Boolean? = null): PyExecResult<String> {
val options = listOf(all to "--all").makeOptions()
return executeAndHandleErrors("show", *options, transformer = ZeroCodeStdoutTransformer)
}
@@ -51,7 +50,7 @@ class HatchConfig(runtime: HatchRuntime) : HatchCommand("config", runtime) {
/**
* Update the config file with any new fields
*/
suspend fun update(): Result<String, ExecError> {
suspend fun update(): PyExecResult<String> {
return executeAndHandleErrors("update", transformer = ZeroCodeStdoutTransformer)
}
}
@@ -3,8 +3,7 @@ package com.intellij.python.hatch.cli
import com.intellij.python.community.execService.ZeroCodeStdoutTransformer
import com.intellij.python.hatch.runtime.HatchRuntime
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.ExecError
import com.jetbrains.python.errorProcessing.PyExecResult
enum class Scope(val options: Array<String>) {
All(emptyArray()),
@@ -19,7 +18,7 @@ class HatchDep(runtime: HatchRuntime) : HatchCommand("dep", runtime) {
/**
* Output a hash of the currently defined dependencies
**/
suspend fun hash(scope: Scope = Scope.All): Result<String, ExecError> {
suspend fun hash(scope: Scope = Scope.All): PyExecResult<String> {
return executeAndHandleErrors("hash", *scope.options, transformer = ZeroCodeStdoutTransformer)
}
@@ -38,7 +37,7 @@ class HatchDepShow(runtime: HatchRuntime) : HatchCommand(arrayOf("dep", "show"),
*
* @param features only show the dependencies of the specified features
*/
suspend fun requirements(scope: Scope = Scope.All, features: List<String>? = null): Result<String, ExecError> {
suspend fun requirements(scope: Scope = Scope.All, features: List<String>? = null): PyExecResult<String> {
val options = features?.flatMap { listOf("--feature", it) }?.toTypedArray() ?: arrayOf("--all")
return executeAndHandleErrors("requirements", *scope.options, *options, transformer = ZeroCodeStdoutTransformer)
}
@@ -46,7 +45,7 @@ class HatchDepShow(runtime: HatchRuntime) : HatchCommand(arrayOf("dep", "show"),
/**
* Enumerate dependencies in a tabular format.
*/
suspend fun table(scope: Scope = Scope.All): Result<String, ExecError> {
suspend fun table(scope: Scope = Scope.All): PyExecResult<String> {
val options = listOf(null to "--lines", true to "--ascii").makeOptions()
return executeAndHandleErrors("table", *scope.options, *options, transformer = ZeroCodeStdoutTransformer)
}
@@ -8,6 +8,7 @@ import com.intellij.python.hatch.runtime.HatchRuntime
import com.jetbrains.python.PythonHomePath
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.ExecError
import com.jetbrains.python.errorProcessing.PyExecResult
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@@ -129,7 +130,7 @@ class HatchEnv(runtime: HatchRuntime) : HatchCommand("env", runtime) {
*
* @return true if created, false if already exists
*/
suspend fun create(envName: String? = null): Result<CreateResult, ExecError> {
suspend fun create(envName: String? = null): PyExecResult<CreateResult> {
val arguments = if (envName == null) emptyArray() else arrayOf(envName)
return executeAndHandleErrors("create", *arguments) {
val actualEnvName = envName ?: DEFAULT_ENV_NAME
@@ -147,7 +148,7 @@ class HatchEnv(runtime: HatchRuntime) : HatchCommand("env", runtime) {
*
* @return path to environment
*/
suspend fun find(envName: String? = null): Result<PythonHomePath?, ExecError> {
suspend fun find(envName: String? = null): PyExecResult<PythonHomePath?> {
val arguments = if (envName == null) emptyArray() else arrayOf(envName)
return executeAndHandleErrors("find", *arguments) {
when (it.exitCode) {
@@ -182,7 +183,7 @@ class HatchEnv(runtime: HatchRuntime) : HatchCommand("env", runtime) {
* - [RemoveResult.CantRemoveActiveEnvironment] if the environment cannot be removed because it is currently active.
* - An error wrapped in [ExecError] in case of execution failure.
*/
suspend fun remove(envName: String? = null): Result<RemoveResult, ExecError> {
suspend fun remove(envName: String? = null): PyExecResult<RemoveResult> {
val arguments = if (envName == null) emptyArray() else arrayOf(envName)
return executeAndHandleErrors("remove", *arguments) {
val actualEnvName = envName ?: DEFAULT_ENV_NAME
@@ -204,7 +205,7 @@ class HatchEnv(runtime: HatchRuntime) : HatchCommand("env", runtime) {
* - [HatchDetailedEnvironments] if operation is successful.
* - An error wrapped in [ExecError] if an execution failure occurs.
*/
suspend fun showWithDetails(vararg envs: String): Result<HatchDetailedEnvironments, ExecError> {
suspend fun showWithDetails(vararg envs: String): PyExecResult<HatchDetailedEnvironments> {
return executeAndHandleErrors("show", "--json", *envs) { processOutput ->
val output = processOutput.takeIf { it.exitCode == 0 }?.stdoutString
?: return@executeAndHandleErrors Result.failure(null)
@@ -231,7 +232,7 @@ class HatchEnv(runtime: HatchRuntime) : HatchCommand("env", runtime) {
* - [HatchDetailedEnvironments] if operation is successful.
* - An error wrapped in [ExecError] if an execution failure occurs.
*/
suspend fun show(vararg envs: String, internal: Boolean = false): Result<HatchEnvironments, ExecError> {
suspend fun show(vararg envs: String, internal: Boolean = false): PyExecResult<HatchEnvironments> {
val options = listOf(internal to "--internal").makeOptions()
return executeAndMatch("show", "--ascii", *options, *envs, expectedOutput = SHOW_RESPONSE_REGEX) { matchResult ->
@@ -4,7 +4,7 @@ package com.intellij.python.hatch.cli
import com.intellij.platform.eel.provider.utils.stdoutString
import com.intellij.python.hatch.runtime.HatchRuntime
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.ExecError
import com.jetbrains.python.errorProcessing.PyExecResult
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@@ -62,7 +62,7 @@ class HatchProject(runtime: HatchRuntime) : HatchCommand("project", runtime) {
/**
* Display project metadata
*/
suspend fun metadata(): Result<Metadata, ExecError> {
suspend fun metadata(): PyExecResult<Metadata> {
return executeAndHandleErrors("metadata") { processOutput ->
val output = processOutput.takeIf { it.exitCode == 0 }?.stdoutString
?: return@executeAndHandleErrors Result.failure(null)
@@ -8,7 +8,7 @@ import com.intellij.platform.eel.provider.utils.stdoutString
import com.intellij.python.hatch.cli.HatchPython.PythonInstallResponse.AbortReason
import com.intellij.python.hatch.runtime.HatchRuntime
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.ExecError
import com.jetbrains.python.errorProcessing.PyExecResult
import java.nio.file.Path
/**
@@ -26,7 +26,7 @@ class HatchPython(runtime: HatchRuntime) : HatchCommand("python", runtime) {
* @param parent Show the parent directory of the Python binary
* @param dir The directory in which distributions reside
*/
suspend fun find(name: String, parent: Boolean? = null, dir: String? = null): Result<Path?, ExecError> {
suspend fun find(name: String, parent: Boolean? = null, dir: String? = null): PyExecResult<Path?> {
val options = listOf(parent to "--parent").makeOptions() + buildDirOption(dir)
return executeAndHandleErrors("find", *options, name) { output ->
@@ -129,7 +129,7 @@ class HatchPython(runtime: HatchRuntime) : HatchCommand("python", runtime) {
private: Boolean? = null,
update: Boolean? = null,
dir: String? = null,
): Result<PythonInstallResponse, ExecError> {
): PyExecResult<PythonInstallResponse> {
val options = listOf(update to "--update", private to "--private").makeOptions() + buildDirOption(dir)
return executeAndHandleErrors("install", *options, *names) { output ->
Result.success(parsePythonInstallCommandOutput(output))
@@ -144,7 +144,7 @@ class HatchPython(runtime: HatchRuntime) : HatchCommand("python", runtime) {
* @param names Distributions to remove, you may select `all` to install all compatible distributions
* @param dir The directory in which distributions reside
*/
suspend fun remove(vararg names: String = ALL_NAMES, dir: String? = null): Result<PythonRemoveResponse, ExecError> {
suspend fun remove(vararg names: String = ALL_NAMES, dir: String? = null): PyExecResult<PythonRemoveResponse> {
return executeAndHandleErrors("remove", *buildDirOption(dir), *names) { processOutput ->
val output = processOutput.stderrString
val notInstalledRegex = Regex("""^Distribution is not installed: (.*)$""", RegexOption.MULTILINE)
@@ -165,7 +165,7 @@ class HatchPython(runtime: HatchRuntime) : HatchCommand("python", runtime) {
* @param dir The directory in which distributions reside
* @return Name to Version as a map
*/
suspend fun show(dir: String? = null): Result<ShowResponse, ExecError> {
suspend fun show(dir: String? = null): PyExecResult<ShowResponse> {
val nameToVersionRegex = """\|\s+([^|\s]+)\s+\|\s+([^|\s]+)\s+\|""".toRegex()
fun parseNameToVersions(payload: String) = nameToVersionRegex.findAll(payload).associate {
val (name, version) = it.destructured
@@ -200,7 +200,7 @@ class HatchPython(runtime: HatchRuntime) : HatchCommand("python", runtime) {
* @param names Distributions to update, you may select `all` to install all compatible distributions
* @param dir The directory in which distributions reside
*/
suspend fun update(vararg names: String = ALL_NAMES, dir: String? = null): Result<PythonInstallResponse, ExecError> {
suspend fun update(vararg names: String = ALL_NAMES, dir: String? = null): PyExecResult<PythonInstallResponse> {
return executeAndHandleErrors("update", *buildDirOption(dir), *names) { output ->
Result.success(parsePythonInstallCommandOutput(output))
}
@@ -7,7 +7,7 @@ import com.intellij.python.hatch.runtime.HatchRuntime
import com.intellij.util.Url
import com.intellij.util.Urls
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.ExecError
import com.jetbrains.python.errorProcessing.PyExecResult
/**
* Manage environment dependencies
@@ -17,7 +17,7 @@ class HatchSelf(runtime: HatchRuntime) : HatchCommand("self", runtime) {
/**
* Generate a pre-populated GitHub issue.
*/
suspend fun report(): Result<Url, ExecError> {
suspend fun report(): PyExecResult<Url> {
return executeAndHandleErrors("report", "--no-open") { processOutput ->
val output = processOutput.takeIf { it.exitCode == 0 }?.stdoutString?.trim()
?: return@executeAndHandleErrors Result.failure(null)
@@ -34,10 +34,10 @@ class HatchSelf(runtime: HatchRuntime) : HatchCommand("self", runtime) {
/**
* Restore the installation
*/
fun restore(): Result<String, ExecError> = TODO()
fun restore(): PyExecResult<String> = TODO()
/**
* Install the latest version
*/
fun update(): Result<String, ExecError> = TODO()
fun update(): PyExecResult<String> = TODO()
}
@@ -9,7 +9,7 @@ import com.intellij.python.hatch.cli.HatchCli
import com.jetbrains.python.PythonBinary
import com.jetbrains.python.PythonHomePath
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.ExecError
import com.jetbrains.python.errorProcessing.PyExecResult
import com.jetbrains.python.errorProcessing.PyResult
import com.jetbrains.python.resolvePythonBinary
import java.nio.file.Path
@@ -55,11 +55,11 @@ class HatchRuntime(
* Pure execution of [hatchBinary] with command line [arguments] and [execOptions] by [execService]
* Doesn't make any validation of stdout/stderr content.
*/
internal suspend fun <T> execute(vararg arguments: String, processOutputTransformer: ProcessOutputTransformer<T>): Result<T, ExecError> {
internal suspend fun <T> execute(vararg arguments: String, processOutputTransformer: ProcessOutputTransformer<T>): PyExecResult<T> {
return execService.execute(hatchBinary, arguments.toList(), execOptions, processOutputTransformer = processOutputTransformer)
}
internal suspend fun <T> executeInteractive(vararg arguments: String, processSemiInteractiveFun: ProcessSemiInteractiveFun<T>): Result<T, ExecError> {
internal suspend fun <T> executeInteractive(vararg arguments: String, processSemiInteractiveFun: ProcessSemiInteractiveFun<T>): PyExecResult<T> {
return execService.executeInteractive(hatchBinary, arguments.toList(), execOptions, processSemiInteractiveHandler(code = processSemiInteractiveFun))
}
@@ -5,13 +5,12 @@ import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.python.hatch.HatchService
import com.intellij.python.hatch.getHatchService
import com.jetbrains.python.errorProcessing.PyError
import com.jetbrains.python.errorProcessing.PyResult
import com.jetbrains.python.hatch.sdk.HatchSdkAdditionalData
import com.jetbrains.python.hatch.sdk.isHatch
import com.jetbrains.python.packaging.management.PythonPackageManager
import com.jetbrains.python.packaging.management.PythonPackageManagerProvider
import com.jetbrains.python.packaging.pip.PipPythonPackageManager
import com.jetbrains.python.Result
internal class HatchPackageManager(project: Project, sdk: Sdk) : PipPythonPackageManager(project, sdk) {
fun getSdkAdditionalData(): HatchSdkAdditionalData {
@@ -21,7 +20,7 @@ internal class HatchPackageManager(project: Project, sdk: Sdk) : PipPythonPackag
"but was ${sdk.sdkAdditionalData?.javaClass?.name}")
}
suspend fun getHatchService(): Result<HatchService, PyError> {
suspend fun getHatchService(): PyResult<HatchService> {
val data = getSdkAdditionalData()
val workingDirectory = data.hatchWorkingDirectory
return workingDirectory.getHatchService(hatchEnvironmentName = data.hatchEnvironmentName)
@@ -4,8 +4,7 @@ package com.jetbrains.python.hatch.packaging
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.python.hatch.HATCH_TOML
import com.intellij.python.pyproject.PY_PROJECT_TOML
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.PyError
import com.jetbrains.python.errorProcessing.PyResult
import com.jetbrains.python.packaging.management.PythonPackageManagerAction
import com.jetbrains.python.packaging.management.getPythonPackageManager
import kotlin.text.Regex.Companion.escape
@@ -17,7 +16,7 @@ internal sealed class HatchPackageManagerAction : PythonPackageManagerAction<Hat
}
internal class HatchRunAction() : HatchPackageManagerAction() {
override suspend fun execute(e: AnActionEvent, manager: HatchPackageManager): Result<String, PyError> {
override suspend fun execute(e: AnActionEvent, manager: HatchPackageManager): PyResult<String> {
val service = manager.getHatchService().getOr { return it }
return service.syncDependencies()
}
@@ -68,7 +68,7 @@ abstract class PythonPackageManagerAction<T : PythonPackageManager, V> : DumbAwa
*
* @return [Result] which contains the successful result of type [V] or an error of type [PyError] if it fails.
*/
protected abstract suspend fun execute(e: AnActionEvent, manager: T): Result<V, PyError>
protected abstract suspend fun execute(e: AnActionEvent, manager: T): PyResult<V>
override fun update(e: AnActionEvent) {
val isWatchedFile = e.editor()?.virtualFile?.name?.let { fileNamesPattern.matches(it) } ?: false
@@ -89,7 +89,7 @@ abstract class PythonPackageManagerAction<T : PythonPackageManager, V> : DumbAwa
document?.reloadIntentions(manager.project)
}
private suspend fun executeScenarioWithinProgress(manager: T, e: AnActionEvent, document: Document?): Result<V, PyError> {
private suspend fun executeScenarioWithinProgress(manager: T, e: AnActionEvent, document: Document?): PyResult<V> {
return reportSequentialProgress(2) { reporter ->
reporter.itemStep {
execute(e, manager)
@@ -2,8 +2,7 @@
package com.jetbrains.python.poetry.packaging
import com.intellij.openapi.actionSystem.AnActionEvent
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.PyError
import com.jetbrains.python.errorProcessing.PyResult
import com.jetbrains.python.errorProcessing.asPythonResult
import com.jetbrains.python.packaging.management.PythonPackageManagerAction
import com.jetbrains.python.packaging.management.getPythonPackageManager
@@ -15,18 +14,18 @@ internal sealed class PoetryPackageManagerAction : PythonPackageManagerAction<Po
}
internal class PoetryLockAction() : PoetryPackageManagerAction() {
override suspend fun execute(e: AnActionEvent, manager: PoetryPackageManager): Result<String, PyError> {
override suspend fun execute(e: AnActionEvent, manager: PoetryPackageManager): PyResult<String> {
return runPoetryWithManager(manager, listOf("lock"))
}
}
internal class PoetryUpdateAction() : PoetryPackageManagerAction() {
override suspend fun execute(e: AnActionEvent, manager: PoetryPackageManager): Result<String, PyError> {
override suspend fun execute(e: AnActionEvent, manager: PoetryPackageManager): PyResult<String> {
return runPoetryWithManager(manager, listOf("update"))
}
}
private suspend fun runPoetryWithManager(manager: PoetryPackageManager, args: List<String>): Result<String, PyError> {
private suspend fun runPoetryWithManager(manager: PoetryPackageManager, args: List<String>): PyResult<String> {
val result = runPoetryWithSdk(manager.sdk, *args.toTypedArray())
return result.asPythonResult()
}
@@ -9,7 +9,7 @@ import com.intellij.python.community.execService.ExecService
import com.intellij.python.community.execService.ProcessEvent
import com.intellij.python.community.execService.WhatToExec
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.ExecError
import com.jetbrains.python.errorProcessing.PyExecResult
import org.jetbrains.annotations.ApiStatus.Internal
import java.nio.file.Path
@@ -24,7 +24,7 @@ import java.nio.file.Path
* @return A [Result] object containing the output of the command execution.
*/
@Internal
suspend fun runExecutableWithProgress(executable: Path, workDir: Path?, vararg args: String): Result<String, ExecError> {
suspend fun runExecutableWithProgress(executable: Path, workDir: Path?, vararg args: String): PyExecResult<String> {
val ansiDecoder = AnsiEscapeDecoder()
reportRawProgress { reporter ->
return ExecService().execGetStdout(WhatToExec.Binary(executable), args.toList(), ExecOptions(workingDirectory = workDir), procListener = {
@@ -26,7 +26,10 @@ import com.jetbrains.python.packaging.common.PythonPackage
import com.jetbrains.python.pathValidation.PlatformAndRoot
import com.jetbrains.python.pathValidation.ValidationRequest
import com.jetbrains.python.pathValidation.validateExecutableFile
import com.jetbrains.python.sdk.*
import com.jetbrains.python.sdk.PyDetectedSdk
import com.jetbrains.python.sdk.associatedModulePath
import com.jetbrains.python.sdk.basePath
import com.jetbrains.python.sdk.runExecutableWithProgress
import com.jetbrains.python.venvReader.VirtualEnvReader
import io.github.z4kn4fein.semver.Version
import io.github.z4kn4fein.semver.toVersion
+13 -12
View File
@@ -1,16 +1,17 @@
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
// Copyright 2000-2025 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.sdk.uv
import com.jetbrains.python.errorProcessing.PyExecResult
import com.jetbrains.python.errorProcessing.PyResult
import com.jetbrains.python.packaging.common.PythonPackage
import com.jetbrains.python.packaging.common.PythonOutdatedPackage
import com.jetbrains.python.packaging.common.PythonPackage
import com.jetbrains.python.packaging.management.PythonPackageInstallRequest
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Path
@ApiStatus.Internal
interface UvCli {
suspend fun runUv(workingDir: Path, vararg args: String): PyResult<String>
suspend fun runUv(workingDir: Path, vararg args: String): PyExecResult<String>
}
@ApiStatus.Internal
@@ -22,23 +23,23 @@ interface UvLowLevel {
/**
* Manage project dependencies by adding/removing them to the project along side installation
*/
suspend fun addDependency(name: PythonPackageInstallRequest, options: List<String>): PyResult<Unit>
suspend fun removeDependency(name: PythonPackage): PyResult<Unit>
suspend fun addDependency(name: PythonPackageInstallRequest, options: List<String>): PyExecResult<Unit>
suspend fun removeDependency(name: PythonPackage): PyExecResult<Unit>
/**
* Managing environment packages directly w/o depending or changing the project
*/
suspend fun installPackage(name: PythonPackageInstallRequest, options: List<String>): PyResult<Unit>
suspend fun uninstallPackage(name: PythonPackage): PyResult<Unit>
suspend fun installPackage(name: PythonPackageInstallRequest, options: List<String>): PyExecResult<Unit>
suspend fun uninstallPackage(name: PythonPackage): PyExecResult<Unit>
suspend fun listPackages(): PyResult<List<PythonPackage>>
suspend fun listPackages(): PyExecResult<List<PythonPackage>>
suspend fun listOutdatedPackages(): PyResult<List<PythonOutdatedPackage>>
suspend fun isProjectSynced(inexact: Boolean): PyResult<Boolean>
suspend fun isScriptSynced(inexact: Boolean, scriptPath: Path): PyResult<ScriptSyncCheckResult>
suspend fun isProjectSynced(inexact: Boolean): PyExecResult<Boolean>
suspend fun isScriptSynced(inexact: Boolean, scriptPath: Path): PyExecResult<ScriptSyncCheckResult>
suspend fun sync(): Result<String>
suspend fun lock(): Result<String>
suspend fun sync(): PyExecResult<String>
suspend fun lock(): PyExecResult<String>
}
@ApiStatus.Internal
@@ -3,16 +3,13 @@ package com.jetbrains.python.sdk.uv
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.jetbrains.python.errorProcessing.PyExecResult
import com.jetbrains.python.errorProcessing.asKotlinResult
import com.jetbrains.python.onSuccess
import com.jetbrains.python.packaging.common.PythonOutdatedPackage
import com.jetbrains.python.packaging.common.PythonPackage
import com.jetbrains.python.packaging.common.PythonRepositoryPackageSpecification
import com.jetbrains.python.packaging.management.PythonPackageInstallRequest
import com.jetbrains.python.packaging.management.PythonPackageManager
import com.jetbrains.python.packaging.management.PythonPackageManagerProvider
import com.jetbrains.python.packaging.management.PythonRepositoryManager
import com.jetbrains.python.packaging.management.toInstallRequest
import com.jetbrains.python.packaging.management.*
import com.jetbrains.python.packaging.pip.PipRepositoryManager
import com.jetbrains.python.sdk.uv.impl.createUvCli
import com.jetbrains.python.sdk.uv.impl.createUvLowLevel
@@ -72,11 +69,11 @@ internal class UvPackageManager(project: Project, sdk: Sdk, private val uv: UvLo
return uv.listPackages().asKotlinResult()
}
suspend fun sync(): Result<String> {
suspend fun sync(): PyExecResult<String> {
return uv.sync()
}
suspend fun lock(): Result<String> {
suspend fun lock(): PyExecResult<String> {
return uv.lock()
}
}
@@ -7,9 +7,7 @@ import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.SystemProperties
import com.jetbrains.python.PyBundle
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.ExecError
import com.jetbrains.python.errorProcessing.PyResult
import com.jetbrains.python.errorProcessing.PyExecResult
import com.jetbrains.python.pathValidation.PlatformAndRoot
import com.jetbrains.python.pathValidation.ValidationRequest
import com.jetbrains.python.pathValidation.validateExecutableFile
@@ -41,7 +39,7 @@ private fun validateUvExecutable(uvPath: Path?): ValidationInfo? {
))
}
private suspend fun runUv(uv: Path, workingDir: Path, vararg args: String): Result<String, ExecError> {
private suspend fun runUv(uv: Path, workingDir: Path, vararg args: String): PyExecResult<String> {
return runExecutableWithProgress(uv, workingDir, *args)
}
@@ -58,7 +56,7 @@ private class UvCliImpl(val dispatcher: CoroutineDispatcher, uvPath: Path?) : Uv
uv = path!!
}
override suspend fun runUv(workingDir: Path, vararg args: String): PyResult<String> {
override suspend fun runUv(workingDir: Path, vararg args: String): PyExecResult<String> {
return withContext(dispatcher) {
runUv(uv, workingDir, *args)
}
@@ -1,21 +1,20 @@
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
// Copyright 2000-2025 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.sdk.uv.impl
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.intellij.util.io.delete
import com.jetbrains.python.packaging.management.PythonPackageInstallRequest
import com.jetbrains.python.errorProcessing.ExecError
import com.jetbrains.python.errorProcessing.ExecErrorReason
import com.jetbrains.python.errorProcessing.PyError
import com.jetbrains.python.errorProcessing.PyExecResult
import com.jetbrains.python.errorProcessing.PyResult
import com.jetbrains.python.errorProcessing.asKotlinResult
import com.jetbrains.python.errorProcessing.failure
import com.jetbrains.python.onFailure
import com.jetbrains.python.packaging.common.PythonOutdatedPackage
import com.jetbrains.python.packaging.common.PythonPackage
import com.jetbrains.python.packaging.management.PythonPackageInstallRequest
import com.jetbrains.python.sdk.uv.ScriptSyncCheckResult
import com.jetbrains.python.sdk.uv.UvCli
import com.jetbrains.python.sdk.uv.UvLowLevel
@@ -93,7 +92,7 @@ private class UvLowLevelImpl(val cwd: Path, private val uvCli: UvCli) : UvLowLev
return PyResult.success(pythons)
}
override suspend fun listPackages(): PyResult<List<PythonPackage>> {
override suspend fun listPackages(): PyExecResult<List<PythonPackage>> {
val out = uvCli.runUv(cwd, "pip", "list", "--format", "json")
.getOr { return it }
@@ -128,14 +127,14 @@ private class UvLowLevelImpl(val cwd: Path, private val uvCli: UvCli) : UvLowLev
}
}
override suspend fun installPackage(name: PythonPackageInstallRequest, options: List<String>): PyResult<Unit> {
override suspend fun installPackage(name: PythonPackageInstallRequest, options: List<String>): PyExecResult<Unit> {
uvCli.runUv(cwd, "pip", "install", name.formatPackageName(), *options.toTypedArray())
.onFailure { return PyResult.failure(it) }
return PyExecResult.success(Unit)
}
override suspend fun uninstallPackage(name: PythonPackage): PyResult<Unit> {
override suspend fun uninstallPackage(name: PythonPackage): PyExecResult<Unit> {
// TODO: check if package is in dependencies and reject it
uvCli.runUv(cwd, "pip", "uninstall", name.name)
.onFailure { return PyResult.failure(it) }
@@ -143,21 +142,21 @@ private class UvLowLevelImpl(val cwd: Path, private val uvCli: UvCli) : UvLowLev
return PyExecResult.success(Unit)
}
override suspend fun addDependency(name: PythonPackageInstallRequest, options: List<String>): PyResult<Unit> {
override suspend fun addDependency(name: PythonPackageInstallRequest, options: List<String>): PyExecResult<Unit> {
uvCli.runUv(cwd, "add", name.formatPackageName(), *options.toTypedArray())
.onFailure { return PyResult.failure(it) }
return PyExecResult.success(Unit)
}
override suspend fun removeDependency(name: PythonPackage): PyResult<Unit> {
override suspend fun removeDependency(name: PythonPackage): PyExecResult<Unit> {
uvCli.runUv(cwd, "remove", name.name)
.onFailure { return PyResult.failure(it) }
return PyExecResult.success(Unit)
}
override suspend fun isProjectSynced(inexact: Boolean): PyResult<Boolean> {
override suspend fun isProjectSynced(inexact: Boolean): PyExecResult<Boolean> {
val args = constructSyncArgs(inexact)
uvCli.runUv(cwd, *args.toTypedArray())
@@ -174,7 +173,7 @@ private class UvLowLevelImpl(val cwd: Path, private val uvCli: UvCli) : UvLowLev
return PyExecResult.success(true)
}
override suspend fun isScriptSynced(inexact: Boolean, scriptPath: Path): PyResult<ScriptSyncCheckResult> {
override suspend fun isScriptSynced(inexact: Boolean, scriptPath: Path): PyExecResult<ScriptSyncCheckResult> {
val args = constructSyncArgs(inexact) + listOf("--script", scriptPath.pathString)
uvCli.runUv(cwd, *args.toTypedArray())
@@ -234,12 +233,12 @@ private class UvLowLevelImpl(val cwd: Path, private val uvCli: UvCli) : UvLowLev
return pythons
}
override suspend fun sync(): Result<String> {
return uvCli.runUv(cwd, "sync").asKotlinResult()
override suspend fun sync(): PyExecResult<String> {
return uvCli.runUv(cwd, "sync")
}
override suspend fun lock(): Result<String> {
return uvCli.runUv(cwd, "lock").asKotlinResult()
override suspend fun lock(): PyExecResult<String> {
return uvCli.runUv(cwd, "lock")
}
}
@@ -2,9 +2,7 @@
package com.jetbrains.python.uv.packaging
import com.intellij.openapi.actionSystem.AnActionEvent
import com.jetbrains.python.Result
import com.jetbrains.python.errorProcessing.PyError
import com.jetbrains.python.errorProcessing.asPythonResult
import com.jetbrains.python.errorProcessing.PyResult
import com.jetbrains.python.packaging.management.PythonPackageManagerAction
import com.jetbrains.python.packaging.management.getPythonPackageManager
import com.jetbrains.python.sdk.uv.UvPackageManager
@@ -14,13 +12,13 @@ internal sealed class UvPackageManagerAction : PythonPackageManagerAction<UvPack
}
internal class UvSyncAction() : UvPackageManagerAction() {
override suspend fun execute(e: AnActionEvent, manager: UvPackageManager): Result<String, PyError> {
return manager.sync().asPythonResult()
override suspend fun execute(e: AnActionEvent, manager: UvPackageManager): PyResult<String> {
return manager.sync()
}
}
internal class UvLockAction() : UvPackageManagerAction() {
override suspend fun execute(e: AnActionEvent, manager: UvPackageManager): Result<String, PyError> {
return manager.lock().asPythonResult()
override suspend fun execute(e: AnActionEvent, manager: UvPackageManager): PyResult<String> {
return manager.lock()
}
}