reference Flags

--output-enclosing-context

Accepted by
opengrep scan
Also spelled
--no-output-enclosing-context
Default
false
See also
--json, --dataflow-traces

Adds to each finding the constructs that contain the match, such as functions and classes, from the outermost to the innermost.

In the text output, the simple and vivid skins show them on a line above the matched code, as in in: class UserView › function search. The legacy skin does not show them.

In the JSON output, the extra of each finding gets an enclosing_context array, with the kind, the name, and the start and end of each construct. Without the flag, the field is absent.

Examples

The class and the method of a finding

sql-injection.yaml
rules:  - id: sql-injection    mode: taint    pattern-sources:      - pattern: request.args.get(...)    pattern-sinks:      - pattern: cursor.execute(...)    message: user input reaches a SQL query    languages: [python]    severity: ERROR
views.py
class UserView:    def search(self):        name = request.args.get("name")        cursor.execute("SELECT * FROM users WHERE name = '" + name + "'")
Command and result
$ opengrep scan -q --config sql-injection.yaml --output-enclosing-context views.py
views.py

  error  sql-injection
  user input reaches a SQL query

    in: class UserView › function search
     4: cursor.execute("SELECT * FROM users WHERE name = '" + name + "'")

The context in the JSON output

rule.yaml
rules:  - id: find-eval    pattern: eval(...)    message: found eval    languages: [python]    severity: WARNING
app.py
def handler(user):    eval(user)
Command and result
$ opengrep scan --config rule.yaml --json --output-enclosing-context app.py 2>/dev/null | jq .
{
  "version": "X.Y.Z",
  "results": [
    {
      "check_id": "find-eval",
      "path": "app.py",
      "start": {
        "line": 2,
        "col": 5,
        "offset": 23
      },
      "end": {
        "line": 2,
        "col": 15,
        "offset": 33
      },
      "extra": {
        "metavars": {},
        "message": "found eval",
        "metadata": {},
        "severity": "WARNING",
        "fingerprint": "cc2ee9ac3b87e874db7ede72562f586db0607e44a6ebc8879fc1772bd2699a2f302d90e0cf6bde9dce450cb0891646fb0b3d70263351681e1d2e48ca0d26d960_0",
        "lines": "    eval(user)",
        "is_ignored": false,
        "validation_state": "NO_VALIDATOR",
        "engine_kind": "Opengrep",
        "enclosing_context": [
          {
            "kind": "function",
            "name": "handler",
            "start": {
              "line": 1,
              "col": 1,
              "offset": 0
            },
            "end": {
              "line": 2,
              "col": 15,
              "offset": 33
            }
          }
        ]
      }
    }
  ],
  "errors": [],
  "paths": {
    "scanned": [
      "app.py"
    ]
  },
  "interfile_languages_used": [],
  "skipped_rules": []
}