|
| 1 | +package tools |
| 2 | + |
| 3 | +import ( |
| 4 | + "codacy/cli-v2/config" |
| 5 | + "codacy/cli-v2/plugins" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "os/exec" |
| 9 | + "path/filepath" |
| 10 | +) |
| 11 | + |
| 12 | +// RunSemgrep executes Semgrep analysis on the specified directory |
| 13 | +func RunSemgrep(workDirectory string, toolInfo *plugins.ToolInfo, files []string, outputFile string, outputFormat string) error { |
| 14 | + // Construct base command with -m semgrep to run semgrep module |
| 15 | + cmdArgs := []string{"scan"} |
| 16 | + |
| 17 | + // Add output format if specified |
| 18 | + if outputFormat == "sarif" { |
| 19 | + cmdArgs = append(cmdArgs, "--sarif") |
| 20 | + } |
| 21 | + |
| 22 | + // Define possible Semgrep config file names |
| 23 | + semgrepConfigFiles := []string{".semgrep.yml", ".semgrep.yaml", ".semgrep/semgrep.yml"} |
| 24 | + |
| 25 | + // Check if a config file exists in the expected location and use it if present |
| 26 | + if configFile, exists := ConfigFileExists(config.Config, semgrepConfigFiles...); exists { |
| 27 | + cmdArgs = append(cmdArgs, "--config", configFile) |
| 28 | + } else { |
| 29 | + // add --config auto only if no config file exists |
| 30 | + cmdArgs = append(cmdArgs, "--config", "auto") |
| 31 | + } |
| 32 | + |
| 33 | + // Add files to analyze - if no files specified, analyze current directory |
| 34 | + if len(files) > 0 { |
| 35 | + cmdArgs = append(cmdArgs, files...) |
| 36 | + } else { |
| 37 | + cmdArgs = append(cmdArgs, ".") |
| 38 | + } |
| 39 | + |
| 40 | + cmdArgs = append(cmdArgs, "--disable-version-check") |
| 41 | + |
| 42 | + // Get Semgrep binary from the specified installation path |
| 43 | + semgrepPath := filepath.Join(toolInfo.InstallDir, "venv", "bin", "semgrep") |
| 44 | + |
| 45 | + // Create Semgrep command |
| 46 | + cmd := exec.Command(semgrepPath, cmdArgs...) |
| 47 | + cmd.Dir = workDirectory |
| 48 | + |
| 49 | + if outputFile != "" { |
| 50 | + // If output file is specified, create it and redirect output |
| 51 | + var outputWriter *os.File |
| 52 | + var err error |
| 53 | + outputWriter, err = os.Create(filepath.Clean(outputFile)) |
| 54 | + if err != nil { |
| 55 | + return fmt.Errorf("failed to create output file: %w", err) |
| 56 | + } |
| 57 | + defer outputWriter.Close() |
| 58 | + cmd.Stdout = outputWriter |
| 59 | + } else { |
| 60 | + cmd.Stdout = os.Stdout |
| 61 | + } |
| 62 | + cmd.Stderr = os.Stderr |
| 63 | + |
| 64 | + // Run Semgrep |
| 65 | + if err := cmd.Run(); err != nil { |
| 66 | + // Semgrep returns non-zero exit code when it finds issues, which is expected |
| 67 | + if _, ok := err.(*exec.ExitError); !ok { |
| 68 | + return fmt.Errorf("failed to run semgrep: %w", err) |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return nil |
| 73 | +} |
0 commit comments