Skip to content

Commit

Permalink
chore: cleaning up main and moving stuff around
Browse files Browse the repository at this point in the history
  • Loading branch information
CatalinSnyk committed Dec 20, 2024
1 parent d9811c7 commit 54a78f0
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 42 deletions.
31 changes: 0 additions & 31 deletions cliv2/cmd/cliv2/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import (
cli_errors "github.com/snyk/cli/cliv2/internal/errors"
"github.com/snyk/cli/cliv2/pkg/basic_workflows"
"github.com/snyk/container-cli/pkg/container"
"github.com/snyk/error-catalog-golang-public/snyk_errors"
"github.com/snyk/go-application-framework/pkg/analytics"
"github.com/snyk/go-application-framework/pkg/app"
"github.com/snyk/go-application-framework/pkg/configuration"
Expand Down Expand Up @@ -620,36 +619,6 @@ func MainWithErrorCode() int {
cliAnalytics.GetInstrumentation().SetStatus(analytics.Failure)
}

// Load error out of run-errors.json
filePath := globalConfiguration.GetString(configuration.TEMP_DIR_PATH) + "/typescript-runtime-errors"

// Read the entire file into a byte slice
errDataFromFile, err := os.ReadFile(filePath)
if err != nil {
globalLogger.Printf("Failed to read file: %v", err)
}

// Convert the byte slice to a string and print it
fmt.Println(`LADEBUG`)
fmt.Println(string(errDataFromFile))
cliError := snyk_errors.Error{
ID: uuid.NewString(),
Title: "Unable to set environment",
Description: "The specified environment cannot be used. As a result, the configuration remains unchanged.Provide the correct specifications for the environment and try again.",
StatusCode: 200,
ErrorCode: string(errDataFromFile),
Classification: "ACTIONABLE",
Links: []string{
"https://docs.snyk.io/snyk-cli/commands/config-environment",
},
Level: "error",
Detail: string(errDataFromFile),
}
cliAnalytics.GetInstrumentation().AddError(
cliError,
)
// END error loading

if !globalConfiguration.GetBool(configuration.ANALYTICS_DISABLED) {
sendAnalytics(cliAnalytics, globalLogger)
}
Expand Down
18 changes: 18 additions & 0 deletions cliv2/internal/cliv2/cliv2.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"slices"
"strings"
Expand Down Expand Up @@ -58,6 +59,8 @@ const (
V2_ABOUT Handler = iota
)

const configKeyErrFile = "INTENAL_MY_ERR_FILE"

func NewCLIv2(config configuration.Configuration, debugLogger *log.Logger, ri runtimeinfo.RuntimeInfo) (*CLI, error) {
cacheDirectory := config.GetString(configuration.CACHE_PATH)

Expand Down Expand Up @@ -351,6 +354,8 @@ func PrepareV1EnvironmentVariables(
// Fill environment variables for the legacy CLI from the given configuration.
func fillEnvironmentFromConfig(inputAsMap map[string]string, config configuration.Configuration, args []string) {
inputAsMap[constants.SNYK_INTERNAL_ORGID_ENV] = config.GetString(configuration.ORGANIZATION)
// TODO: pull into constants
inputAsMap["SNYK_ERR_FILE"] = config.GetString(configKeyErrFile)

if config.GetBool(configuration.PREVIEW_FEATURES_ENABLED) {
inputAsMap[constants.SNYK_INTERNAL_PREVIEW_FEATURES_ENABLED] = "1"
Expand Down Expand Up @@ -402,6 +407,9 @@ func (c *CLI) executeV1Default(proxyInfo *proxy.ProxyInfo, passThroughArgs []str
defer cancel()
}

filePath := filepath.Join(c.globalConfig.GetString(configuration.TEMP_DIR_PATH), fmt.Sprintf("err-file-%d", time.Now().Nanosecond()))
c.globalConfig.Set(configKeyErrFile, filePath)

snykCmd, err := c.PrepareV1Command(ctx, c.v1BinaryLocation, passThroughArgs, proxyInfo, c.GetIntegrationName(), GetFullVersion())

if c.DebugLogger.Writer() != io.Discard {
Expand Down Expand Up @@ -447,6 +455,16 @@ func (c *CLI) executeV1Default(proxyInfo *proxy.ProxyInfo, passThroughArgs []str
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return ctx.Err()
}

errDataFromFile, fileErr := os.ReadFile(filePath)
if fileErr != nil {
c.DebugLogger.Printf("Failed to read file: %v", fileErr)
}

c.DebugLogger.Println(`LADEBUG`)
c.DebugLogger.Println(string(errDataFromFile))
// TODO: wrap this in a custom struct/err format that we can use in the

return err
}

Expand Down
5 changes: 1 addition & 4 deletions cliv2/pkg/basic_workflows/legacycli.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,7 @@ func legacycliWorkflow(
if len(apiToken) == 0 {
apiToken = "random"
}
cli.AppendEnvironmentVariables([]string{
constants.SNYK_API_TOKEN_ENV + "=" + apiToken,
"SNYK_TEMP_DIR_PATH=" + config.GetString(configuration.TEMP_DIR_PATH),
})
cli.AppendEnvironmentVariables([]string{constants.SNYK_API_TOKEN_ENV + "=" + apiToken})

err = cli.Init()
if err != nil {
Expand Down
22 changes: 22 additions & 0 deletions src/cli/ipc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { writeFile } from 'fs/promises';
import { ProblemError } from '@snyk/error-catalog-nodejs-public';

// TODO: handle more gracefully
const ERROR_FILE_PATH = process.env.SNYK_ERR_FILE!;

export async function sendError(err: Error): Promise<void> {
const data = serializeError(err);
return await writeFile(ERROR_FILE_PATH, data);
}

// TBD: json format that the erorr get sent as (ProblemErrorJson, JSON API, custom one?)
function serializeError(err: Error): string {
// @ts-expect-error Using this instead of 'instanceof' since the error might be caught from external CLI plugins.
// See: https://github.com/snyk/error-catalog/blob/main/packages/error-catalog-nodejs/src/problem-error.ts#L17-L19
if (err.isErrorCatalogError) {
// NOTE: there's also the JSON API version for this.
return JSON.stringify((err as ProblemError).toProblemJson('instance?'));
}

return JSON.stringify(err, Object.getOwnPropertyNames(err));
}
11 changes: 4 additions & 7 deletions src/cli/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ import { SarifFileOutputEmptyError } from '../lib/errors/empty-sarif-output-erro
import { InvalidDetectionDepthValue } from '../lib/errors/invalid-detection-depth-value';
import { obfuscateArgs } from '../lib/utils';
import { EXIT_CODES } from './exit-codes';
import { sendError } from './ipc';

const isEmpty = require('lodash/isEmpty');

const debug = Debug('snyk');
Expand Down Expand Up @@ -195,12 +197,7 @@ async function handleError(args, error) {
analytics.add('error', true);
analytics.add('command', args.command);
} else {
const errorFilePath = pathLib.join(process.env.SNYK_TEMP_DIR_PATH || getFullPath(''), './typescript-runtime-errors');

// TODO: If error is NOT valid error catalog message transform to match structure
await saveJsonResultsToFile(JSON.stringify(
analyticsError,
), errorFilePath);
sendError(error);
analytics.add('error-message', analyticsError.message);
// Note that error.stack would also contain the error message
// (see https://nodejs.org/api/errors.html#errors_error_stack)
Expand All @@ -220,7 +217,7 @@ async function handleError(args, error) {
return { res, exitCode };
}

function getFullPath(filepathFragment: string): string {
export function getFullPath(filepathFragment: string): string {
if (pathLib.isAbsolute(filepathFragment)) {
return filepathFragment;
} else {
Expand Down

0 comments on commit 54a78f0

Please sign in to comment.