

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 플러그인 API 참조
<a name="sbomgen-plugin-api-reference"></a>

 Inspector-sbomgen Lua 플러그인에 대한 전체 API 참조입니다. 플러그인 작성에 대한 지침은 섹션을 참조하세요[플러그인 개발자 안내서](sbomgen-plugin-developer-guide.md). 테스트는 단원을 참조하십시오[플러그인 테스트 가이드](sbomgen-plugin-testing-guide.md).

## 개요
<a name="sbomgen-plugin-api-reference-overview"></a>

 모든 런타임 제공 함수는 전역 `sbomgen` 테이블(파일 I/O, 정규식, 로깅, 상수 등)을 통해 액세스됩니다. 또한 각 플러그인은 플러그인 수명 주기의 정의된 지점에서 sbomgen 호출을 수행하는 작은 최상위 글로벌 함수 세트(`discover`, `collect``get_scanner_name`, `subscribe_to_event`, 등)를 정의합니다. 이는에 설명되어 있습니다[플러그인 수명 주기 글로벌](#sbomgen-plugin-api-reference-plugin-lifecycle-globals).

 `*_test.lua` 파일 내에서 sbomgen은 테스트 작성자가 검색 → 수집 파이프라인을 구동하고 어설션을 수행할 수 있는 `testing` 글로벌를 추가로 노출합니다. [API 테스트](#sbomgen-plugin-api-reference-testing-api)을(를) 참조하세요.

### 샌드박스 제한 사항
<a name="sbomgen-plugin-api-reference-sandbox-restrictions"></a>

 플러그인은 표준 라이브러리 액세스가 제한된 샌드박스 Lua VM에서 실행됩니다. 다음 Lua 표준 라이브러리 모듈을 **사용할 수 있습니다**.


| **모듈** | **참고** | 
| --- | --- | 
| base | 코어 함수(print, type, tostring, tonumber, pairs, ipairs, pcall, error, select, unpackrawgetrawset, 등). dofile, 및 loadfile는 제거loadstring됩니다. | 
| string | 전체 문자열 조작(string.match, string.find, string.formatstring.gsub, 등) | 
| table | 전체 테이블 조작(table.insert, table.remove, table.sorttable.concat, 등) | 
| math | 전체 수학 라이브러리(math.floor, math.maxmath.min, 등) | 
| package | require()는 사용할 수 있지만 플러그인의 자체 디렉터리 트리 내의 모듈로 제한됩니다. 상위 디렉터리 순회(require("../shared"))가 차단됩니다. package.cpath 및 package.path가 지워집니다. | 

 다음 표준 라이브러리 모듈은 보안 및 안정성을 위해 **명시적으로 허용되지 않습니다**.


| **모듈** | **이유** | 
| --- | --- | 
| io | 직접 파일 시스템 액세스가 차단됩니다. 모든 파일 작업은 아티팩트 유형(디렉터리, 컨테이너, 볼륨 등)에서 일관된 동작을 위해 아티팩트 인터페이스를 통해 라우팅되는 sbomgen.\* 함수를 거쳐야 합니다. | 
| os | 플러그인이 호스트 시스템을 수정하지 못하도록 시스템 수준 작업(os.execute, os.removeos.rename, os.getenv, 등)이 차단됩니다. | 
| debug | Lua VM 내부 검사 또는 수정을 방지하기 위해 디버그 라이브러리가 차단됩니다. | 
| coroutine | 코루틴은 로드되지 않습니다. | 

 이러한 모듈은 VM의 허용 목록에 없으며 플러그인에서 액세스할 수 없습니다.

**참고**  
**중요:** 모든 파일 I/O는 `sbomgen.*` 함수(예: , `sbomgen.read_file``sbomgen.open_file`, `sbomgen.get_file_list`)를 거쳐야 합니다. `io.open` 또는 직접 파일 시스템 액세스를 사용하면 런타임 오류가 발생합니다. `sbomgen` API는 플러그인이 아티팩트 추상화 계층과 상호 작용하도록 하여 디렉터리, 컨테이너 이미지, 아카이브 또는 볼륨을 스캔하든 일관된 동작을 제공합니다.

## 플러그인 수명 주기 글로벌
<a name="sbomgen-plugin-api-reference-plugin-lifecycle-globals"></a>

 플러그인은 특정 최상위 글로벌 함수를 `init.lua` 정의하는 라는 Lua 파일입니다. 이러한 전역은 `sbomgen` 테이블에 **없습니다**. 플러그인이 sbomgen이 호출하도록 정의하는 함수입니다. 유효한 전역 세트는 검색 플러그인과 컬렉션 플러그인 간에 다릅니다. 아래 모든 함수에 대해 플러그인이 이를 생략하면 표에 표시된 기본값이 사용됩니다.

### 검색 플러그인
<a name="sbomgen-plugin-api-reference-discovery-plugins"></a>


| **함수** | **아리티** | **필수** | **기본값(생략된 경우)** | **설명** | 
| --- | --- | --- | --- | --- | 
| discover() | 0 | 예 | — | 이 플러그인이 찾은 파일을 반환합니다. 경로 문자열의 순차적 테이블(단일 이벤트 모드) 또는 값이 경로 테이블(다중 이벤트 모드)인 이벤트 이름 문자열로 키가 지정된 테이블을 반환합니다. | 
| get\_event\_name() | 0 | 아니요 | "lua:{platform}/{category}/{ecosystem}" | 파일이 게시되는 이벤트 이름을 반환합니다. 모든 검색 플러그인에서 고유해야 합니다. | 
| get\_scanner\_name() | 0 | 아니요 | 에코시스템 디렉터리 이름 | 스캐너의 표시 이름을 반환합니다. 모든 검색 플러그인에서 고유해야 합니다. | 
| get\_scanner\_description() | 0 | 아니요 | "Lua discovery plugin: {ecosystem}" | 사람이 읽을 수 있는 설명을 반환합니다. | 
| get\_scanner\_groups() | 0 | 아니요 | 범주 디렉터리에서 파생됨(개발자 가이드 참조) | 스캐너 그룹 문자열 테이블을 반환합니다. sbomgen.groups.\* 상수를 사용합니다. | 
| get\_localhost\_scan\_paths() | 0 | 아니요 | — | 로컬 호스트 아티팩트를 스캔할 때 포함할 파일/디렉터리 경로 테이블을 반환합니다. localhost 스캔에만 참조됩니다. | 

### 컬렉션 플러그인
<a name="sbomgen-plugin-api-reference-collection-plugins"></a>


| **함수** | **아리티** | **필수** | **기본값(생략된 경우)** | **설명** | 
| --- | --- | --- | --- | --- | 
| collect(file\_path) | 1 | 예 | — | 구독된 이벤트에 게시된 파일당 한 번 호출됩니다. 파일을 구문 분석하고를 통해 결과를 내보냅니다sbomgen.push\_package(). 아무것도 반환하지 않습니다. | 
| subscribe\_to\_event() | 0 | 아니요 | "lua:{platform}/{category}/{ecosystem}" | 이 수집기가 구독하는 이벤트 이름을 반환합니다. 해당 검색 플러그인의와 일치해야 합니다get\_event\_name(). | 
| get\_collector\_name() | 0 | 아니요 | 에코시스템 디렉터리 이름 | 수집기의 표시 이름을 반환합니다. 모든 컬렉션 플러그인에서 고유해야 합니다. | 
| get\_collector\_description() | 0 | 아니요 | "" (비어 있음) | 사람이 읽을 수 있는 설명을 반환합니다. | 

## 파일 I/O
<a name="sbomgen-plugin-api-reference-file-i-o"></a>

 모든 파일 작업은 `sbomgen.*` API를 거쳐야 합니다. Lua의 `io` 라이브러리를 통한 직접 파일 시스템 액세스는 사용할 수 없습니다( 참조[샌드박스 제한 사항](#sbomgen-plugin-api-reference-sandbox-restrictions)). `sbomgen` 파일 I/O 함수는 아티팩트 인터페이스를 통해 라우팅되므로 디스크의 디렉터리, 컨테이너 이미지, 압축된 아카이브 또는 마운트된 볼륨을 스캔하든 플러그인이 동일하게 작동합니다.

### `sbomgen.get_file_list()`
<a name="sbomgen-plugin-api-reference-sbomgen-get-file-list"></a>

 아티팩트의 모든 파일 경로를 문자열 테이블로 반환합니다.
+ **반환:** `{string, ...}`- 절대 파일 경로 문자열 테이블
+ **성능:**이 함수는 아티팩트의 모든 파일 경로를 Lua VM에 Lua 문자열로 복사합니다. 대용량 아티팩트(예: 300K 개 이상의 파일을 사용한 localhost 스캔)의 경우이 작업에만 몇 초가 걸립니다. Lua에서 반환된 테이블을 로 반복하면 오버헤드`string.match()`가 추가됩니다. 전체 스캔에는 15초 이상이 걸릴 수 있습니다. **아티팩트에 파일이 많을수록 플러그인 속도가 느려집니다.**

**참고**  
**가능하면 다음과 같은 대상 대안을 선호합니다.**  


| **함수** | **다음과 같은 경우에 사용합니다.** | 
| --- | --- | 
| sbomgen.find\_files\_by\_name() | 일치시킬 정확한 파일 이름(예: , )을 알고 있습니다. "requirements.txt" "curl"  | 
| sbomgen.find\_files\_by\_name\_icase() | 위와 동일하지만 대소문자를 구분하지 않음 | 
| sbomgen.find\_files\_by\_suffix() | 경로 접미사(예: , "/pom.properties""curlver.h")와 일치해야 합니다. | 
| sbomgen.find\_files\_by\_path\_regex() | 전체 경로 정규식 일치가 필요합니다. | 
| sbomgen.glob\_find\_files() | glob 스타일 기본 이름 일치가 필요합니다. | 
이러한 함수는 Lua VM 외부에서 매칭을 수행하고 매칭된 경로만 반환하여 300K-file 아티팩트에서도 1밀리초 이내에 완료됩니다. 일치하는 로직을 위의 항목 중 하나로 표현할 수 없는 `get_file_list()` 경우에만 사용합니다.

```
-- AVOID in discovery plugins when possible:
local files = sbomgen.get_file_list()
for _, f in ipairs(files) do
    if string.match(f, "pattern$") then ... end
end

-- PREFER:
local matches = sbomgen.find_files_by_name({"target-file.txt"})
```

### `sbomgen.read_file(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-read-file-path"></a>

 파일의 전체 내용을 읽고 문자열로 반환합니다.
+ **다음을 반환합니다.** `string, err` 
+ 실패 시: `nil, error_string`

```
local content, err = sbomgen.read_file("/app/package.json")
if err then
    sbomgen.log_error("read failed: " .. err)
    return
end
```

### `sbomgen.open_file(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-open-file-path"></a>

 읽기 스트리밍을 위한 파일을 엽니다. FileHandle 객체를 반환합니다. 전체 콘텐츠를 메모리에 로드하는 것이 실용적이지 않은 대용량 파일에 사용합니다.
+ **다음을 반환합니다.** `FileHandle, err` 

```
local fh, err = sbomgen.open_file(path)
if err then return end
local line = fh:read_line()
while line do
    -- process line
    line = fh:read_line()
end
fh:close()
```

### `sbomgen.glob_find_files(pattern)`
<a name="sbomgen-plugin-api-reference-sbomgen-glob-find-files-pattern"></a>

 Go `filepath.Match` glob 패턴과 일치하는 파일을 반환합니다. 패턴은 기본 파일 이름과 일치합니다.
+ **다음을 반환합니다.** `{string, ...}, err` 

```
local files, err = sbomgen.glob_find_files("*.txt")
```

 전체 경로 패턴 일치`string.match`를 위해와 `sbomgen.get_file_list()` 함께를 사용합니다.

### `sbomgen.find_files_by_name(names)`
<a name="sbomgen-plugin-api-reference-sbomgen-find-files-by-name-names"></a>

 기본 이름(마지막 경로 구성 요소)이 지정된 이름 중 하나와 정확히 일치하는 파일을 반환합니다. 반복 및 비교는 Go에서 수행되므로 Lua`sbomgen.get_file_list()`에서 반복하는 것보다 훨씬 빠릅니다.
+ **파라미터:** `names` - 문자열 테이블(일치할 기본 이름)
+ **반환:** `{string, ...}`- 일치하는 파일 경로(오류 튜플 없음)

```
local curl_bins = sbomgen.find_files_by_name({"curl", "curl.exe"})
local headers = sbomgen.find_files_by_name({"curlver.h"})
```

### `sbomgen.find_files_by_name_icase(names)`
<a name="sbomgen-plugin-api-reference-sbomgen-find-files-by-name-icase-names"></a>

 기본 이름이 지정된 이름 중 하나와 일치하고 대/소문자를 무시하는 파일을 반환합니다. 예를 들어는 `VERSION`, 및 `Version`와 `"version"` 일치합니다`version`. 와 마찬가지로 `find_files_by_name`일치는 Lua VM 외부에서 발생합니다.
+ **파라미터:** `names` - 문자열 테이블(일치할 기본 이름, 대/소문자를 구분하지 않음)
+ **반환:** `{string, ...}`- 일치하는 파일 경로(오류 튜플 없음)

```
local version_files = sbomgen.find_files_by_name_icase({"version"})
local war_files = sbomgen.find_files_by_name_icase({"jenkins.war"})
```

### `sbomgen.find_files_by_suffix(suffixes)`
<a name="sbomgen-plugin-api-reference-sbomgen-find-files-by-suffix-suffixes"></a>

 전체(forward-slash-normalized) 경로가 지정된 접미사 중 하나로 끝나는 파일을 반환합니다. 와 마찬가지로 `find_files_by_name`일치는 Lua VM 외부에서 발생합니다.
+ **파라미터:** `suffixes` - 문자열 테이블(일치할 경로 접미사)
+ **반환:** `{string, ...}`- 일치하는 파일 경로(오류 튜플 없음)

```
local pom_files = sbomgen.find_files_by_suffix({"/pom.properties"})
local release_headers = sbomgen.find_files_by_suffix({"ap_release.h", "opensslv.h"})
```

### `sbomgen.find_files_by_path_regex(patterns)`
<a name="sbomgen-plugin-api-reference-sbomgen-find-files-by-path-regex-patterns"></a>

 forward-slash-normalized 경로가 지정된 Go(RE2) 정규식 패턴과 일치하는 파일을 반환합니다. 일치는 Lua VM 외부에서 발생하므로 대용량 파일 목록에서 효율적입니다.
+ **파라미터:** `patterns`- Go 정규식 문자열 테이블
+ **반환:** `{string, ...}`- 일치하는 파일 경로(오류 튜플 없음)
+ **Raises:** 패턴이 컴파일되지 않는 경우 Lua 오류 발생

```
local configs = sbomgen.find_files_by_path_regex({"/etc/.*\\.conf$", "/opt/.*/config\\.json$"})
```

### 성능: `find_files_by_*` vs `get_file_list`
<a name="sbomgen-plugin-api-reference-performance-find-files-by-vs-get-file-list"></a>

 검색 플러그인의 경우 Lua`get_file_list()`에서 `find_files_by_name``find_files_by_suffix`, 또는를 반복하는 `find_files_by_path_regex` 것보다 선호합니다. 300K 파일을 사용한 localhost 스캔에서 Lua의 파일 목록을 로 반복하는 데 약 15초가 `string.match()` 걸리고는 1밀리초 이내에 `find_files_by_name` 완료됩니다. 차이점은가 모든 파일 경로를 Lua VM에 문자열로 `get_file_list()` 복사한 다음 Lua가 각 파일의 루프 및 패턴 일치를 해석한다는 것입니다. `find_files_by_*` 함수는 Lua VM 외부에서 일치하는를 수행하고 일치하는 경로만 반환하므로 복사와 경로별 해석 오버헤드가 모두 발생하지 않습니다.

 기본 이름, 접미사 또는 정규식 일치로 표현할 수 없는 사용자 지정 일치 로직이 필요한 `get_file_list()` 경우에만를 사용합니다.

### `sbomgen.read_dir(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-read-dir-path"></a>

 디렉터리의 항목을 나열합니다.
+ **다음을 반환합니다.** `{{name, is_dir}, ...}, err` 

```
local entries, err = sbomgen.read_dir("/app/node_modules")
if err then return end
for _, e in ipairs(entries) do
    if e.is_dir then
        sbomgen.log_debug("directory: " .. e.name)
    end
end
```

### `sbomgen.file_stat(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-file-stat-path"></a>

 파일에 대한 메타데이터를 반환합니다.
+ **다음을 반환합니다.** `{is_regular, is_dir, size}, err` 

```
local info, err = sbomgen.file_stat(path)
if err then return end
if info.is_regular and info.size > 0 then
    -- process file
end
```

### `sbomgen.read_zip_entry(path, entry_path)`
<a name="sbomgen-plugin-api-reference-sbomgen-read-zip-entry-path-entry-path"></a>

 ZIP, JAR 또는 WAR 아카이브에서 단일 항목을 읽습니다.
+ **다음을 반환합니다.** `string, err` 

```
local manifest, err = sbomgen.read_zip_entry(
    "/app/lib/example.jar",
    "META-INF/MANIFEST.MF"
)
```

### `sbomgen.search_binary(path, regex)`
<a name="sbomgen-plugin-api-reference-sbomgen-search-binary-path-regex"></a>

 파일을 ELF, PE 또는 Mach-O 바이너리로 구문 분석하고 기본 상수/변수 섹션에서 Go 정규식 일치를 검색합니다.
+ **반환: **`string|nil, err`- 일치하는 문자열 또는 일치하지 않는 경우 nil을 반환합니다.

```
local version, err = sbomgen.search_binary(path, "Version:\\s+([\\d.]+)")
if version then
    sbomgen.log_info("found version: " .. version)
end
```

### `sbomgen.search_binary_all(path, regex [, n])`
<a name="sbomgen-plugin-api-reference-sbomgen-search-binary-all-path-regex-n"></a>

 파일을 ELF, PE 또는 Mach-O 바이너리로 구문 분석하고 기본 상수/변수 섹션에서 모든 고유한 첫 번째 캡처 그룹 일치 항목을 반환합니다. 를 전달`n`하여 결과를 제한합니다.
+ **반환:** `{string, ...}|nil, err`- 일치하는 문자열 테이블 또는 일치하는 문자열이 없는 경우 nil

```
local versions, err = sbomgen.search_binary_all(path, "version[= ]+([\\d.]+)", 5)
if versions then
    for _, v in ipairs(versions) do
        sbomgen.log_info("found: " .. v)
    end
end
```

### `sbomgen.search_binary_raw(path, regex)`
<a name="sbomgen-plugin-api-reference-sbomgen-search-binary-raw-path-regex"></a>

 전체 이진 파일에서 특정 섹션에 국한되지 않는 첫 번째 정규식 일치를 검색합니다. 예를 들어 버전 문자열이 비표준 섹션에 있는 경우와 같이 섹션 기반 검색(`search_binary`)이 충분하지 않은 경우를 사용합니다.
+ **반환: - 일치하는 문자열 또는 일치하지 않는 경우 nil을 반환합니다**. `string|nil, err` 

```
local version, err = sbomgen.search_binary_raw(path, "ProductVersion[\\x00\\s]+([\\d.]+)")
```

## FileHandle 메서드
<a name="sbomgen-plugin-api-reference-filehandle-methods"></a>

 FileHandle 객체는에서 반환됩니다`sbomgen.open_file()`.

### `fh:read_line()`
<a name="sbomgen-plugin-api-reference-fh-read-line"></a>

 다음 줄을 읽습니다(새 줄 문자 제외). EOF`nil`에서를 반환합니다.
+ **다음을 반환합니다.** `string|nil, err` 

### `fh:read(n)`
<a name="sbomgen-plugin-api-reference-fh-read-n"></a>

 최대 `n`바이트까지 읽습니다. EOF`nil`에서를 반환합니다.
+ **다음을 반환합니다.** `string|nil, err` 

### `fh:close()`
<a name="sbomgen-plugin-api-reference-fh-close"></a>

 파일 핸들을 닫습니다. 완료되면 항상 핸들을 닫습니다.

## 바이너리 유틸리티
<a name="sbomgen-plugin-api-reference-binary-utilities"></a>

### `sbomgen.sha256(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-sha256-path"></a>

 파일 콘텐츠의 16진수 인코딩 SHA-256 해시를 반환합니다.
+ **다음을 반환합니다.** `string, err` 

```
local hash, err = sbomgen.sha256("/app/bin/server")
if hash then
    sbomgen.log_info("SHA-256: " .. hash)
end
```

### `sbomgen.contains_bytes(path, patterns)`
<a name="sbomgen-plugin-api-reference-sbomgen-contains-bytes-path-patterns"></a>

 파일에 지정된 각 바이트 패턴이 포함되어 있는지 확인합니다. 입력 패턴과 동일한 순서로 부울 테이블을 반환합니다.
+ **다음을 반환합니다.** `{bool, ...}, err` 

```
local results, err = sbomgen.contains_bytes(path, {
    "\xff Go buildinf:",   -- Go build identifier
    "/rustc/",             -- Rust build identifier
})
if results then
    local is_go = results[1]
    local is_rust = results[2]
end
```

### `sbomgen.get_pe_version_info(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-get-pe-version-info-path"></a>

 바이너리 파일에서 Windows PE 버전 리소스를 구문 분석합니다. 파일에서 PE 바이너리가 아니거나 버전 리소스가 없는 `nil, err` 경우 버전 필드가 있는 테이블을 반환합니다.
+ **다음을 반환합니다.** `{product_version, file_version, string_table}, err` 

 `product_version` 및 `file_version` 필드는 형식의 PE `FixedFileInfo` 구조에서 가져옵니다`"major.minor.build.revision"`. `string_table` 필드는 로**캘 코드**로 입력되는 중첩 테이블입니다(예: 미국 영어 유니코드의 `"040904B0"` 경우 ). 각 로캘은 PE`StringFileInfo`(`ProductVersion`, `ProductName``FileDescription`, 등)에서 가져온 이름/값 페어 테이블에 매핑됩니다. PE 바이너리는 하나 이상의 로캘을 노출할 수 있습니다.

```
local info, err = sbomgen.get_pe_version_info(file_path)
if err then return end

-- Fixed version fields (always flat)
local product_ver = info.product_version  -- e.g. "25.1.0.0"
local file_ver    = info.file_version     -- e.g. "25.1.0.0"

-- String table — iterate locales, or address a known locale by key
for locale, fields in pairs(info.string_table or {}) do
    sbomgen.log_info(string.format("%s ProductName=%s", locale, fields.ProductName or ""))
end

-- US English Unicode is the most common locale for PE files
local us = (info.string_table or {})["040904B0"]
if us then
    local display_ver = us.ProductVersion  -- e.g. "25.01"
    local name        = us.ProductName     -- e.g. "7-Zip"
end
```

### `sbomgen.parse_product_version(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-parse-product-version-path"></a>

 PE 바이너리의 FixedFileInfo에서 제품 버전 문자열만 반환하는 편의 래퍼입니다. 호출 `get_pe_version_info(path)` 및 읽기와 동일합니다`product_version`.
+ **다음을 반환합니다.** `string, err` 

```
local version, err = sbomgen.parse_product_version(file_path)
if version then
    sbomgen.log_info("product version: " .. version)
end
```

### `sbomgen.parse_file_version(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-parse-file-version-path"></a>

 PE 바이너리의 FixedFileInfo에서 파일 버전 문자열만 반환하는 편리한 래퍼입니다. 호출 `get_pe_version_info(path)` 및 읽기와 동일합니다`file_version`.
+ **다음을 반환합니다.** `string, err` 

```
local version, err = sbomgen.parse_file_version(file_path)
if version then
    sbomgen.log_info("file version: " .. version)
end
```

## 패키지 출력
<a name="sbomgen-plugin-api-reference-package-output"></a>

### `sbomgen.push_package(pkg)`
<a name="sbomgen-plugin-api-reference-sbomgen-push-package-pkg"></a>

 패키지 결과를 SBOM으로 푸시합니다. 컬렉션 플러그인에서만 사용할 수 있습니다.

 이 `pkg` 테이블은 다음 필드를 지원합니다.


| **필드** | **유형** | **필수** | **설명** | 
| --- | --- | --- | --- | 
| name | 문자열 | 예 | 패키지 이름 | 
| version | 문자열 | No | 해결된 버전 문자열 | 
| namespace | 문자열 | No | PURL 네임스페이스(예: , "curl""wordpress/plugin") | 
| purl\_type | 문자열 | 예 | PURL 유형(예: , "pypi", "npm""cargo", "deb", "generic") | 
| component\_type | 문자열 | 예 | CycloneDX 구성 요소 유형, sbomgen.component\_types.\* 상수 사용(예: sbomgen.component\_types.LIBRARY) | 
| qualifiers | 테이블 | 아니요 | 키-값 페어로서의 PURL 한정자(패키지 URL에 표시됨) | 
| properties | 테이블 | 아니요 | 키-값 페어로서의 CycloneDX 구성 요소 속성( 참조[CycloneDX 속성](#sbomgen-plugin-api-reference-cyclonedx-properties)) | 
| children | 테이블 | 아니요 | 중첩된 하위 패키지, 각각 동일한 모양(pkg필수 필드는 재귀적으로 검증됨) | 

```
sbomgen.push_package({
    name = "requests",
    version = "2.28.1",
    purl_type = "pypi",
    component_type = sbomgen.component_types.LIBRARY,
    qualifiers = { example_qualifier = "example_qualifier_value" },
    properties = {
        -- Use your own namespace; amazon:inspector:* is reserved for Amazon Inspector.
        ["acme:example:extra_field"] = "example_value",
    },
})
```

## CycloneDX 속성
<a name="sbomgen-plugin-api-reference-cyclonedx-properties"></a>

 CycloneDX 속성은 SBOM의 구성 요소에 연결된 키-값 메타데이터입니다. PURL 한정자와 구별됩니다.
+ **`qualifiers`** - PURL 한정자입니다. 이는 패키지 URL 문자열(예: `pkg:deb/debian/curl@7.88.1?arch=amd64`)의 일부가 됩니다. 일부 PURL 한정자는 Amazon Inspector에 의미론적 의미를 부여하고 취약성 식별에 영향을 미칩니다. [패키지 URL이란 무엇입니까?를](https://docs.aws.amazon.com/inspector/latest/user/sbom-generator-purl-sbom.html) 참조하세요. - Inspector의 유형별 규칙입니다.
+ **`properties`** - CycloneDX 구성 요소 속성입니다. 이는 SBOM의 `components[].properties` 배열에 나타나며 구성 요소의 식별 방법은 변경되지 않습니다.

### 예약 네임스페이스
<a name="sbomgen-plugin-api-reference-reserved-namespaces"></a>

 CycloneDX 속성 네임스페이스 `amazon:inspector:*` 패밀리는 Amazon Inspector용으로 예약되어 있습니다.
+ `amazon:inspector:sbom_generator:*` - sbomgen 및 내장 스캐너에서 사용됩니다.
+ `amazon:inspector:sbom_scanner:*` - Amazon Inspector 스캔 API에서 사용됩니다.

 **플러그인 정의 속성은 이러한 네임스페이스를 사용해서는 안 됩니다.** 예약된 네임스페이스에 쓰면 Inspector가 의존하는 값과 섀도우가 되거나 충돌할 수 있으며, 취약성 식별 중에 결과 SBOM이 잘못 해석될 수 있습니다. 예약 키의 전체 목록은 [ Amazon Inspector에서 CycloneDX 네임스페이스 사용을 참조하세요](https://docs.aws.amazon.com/inspector/latest/user/cyclonedx-namespace.html).

### 키 이름 지정 규칙
<a name="sbomgen-plugin-api-reference-key-naming-rules"></a>

 에 전달된 속성 키`sbomgen.push_package()`는 다음과 같이 처리됩니다.


| **입력 키** | **SBOM의 결과 키** | **사용자 지정 플러그인에 권장되나요?** | 
| --- | --- | --- | 
| 포함:(예: acme:my\_plugin:field) | 축어적 사용 | 예 - 모든 플러그인 정의 속성을 자체 네임스페이스에 배치합니다. | 
| 아니요:(예: field) | 에 자동 접두사 지정 amazon:inspector:sbom\_generator:field | 아니요 - 예약된 네임스페이스에 씁니다. | 

 정의한 속성 키에 항상 콜론을 하나 이상 포함합니다. 조직 또는 플러그인에 고유한 네임스페이스를 사용합니다(예: `acme:python-pip:*`).

```
properties = {
    -- Custom namespace — safe to use (recommended)
    ["acme:python-pip:manifest_path"] = file_path,
    ["acme:python-pip:pinned"]        = "true",

    -- Fully-qualified key outside amazon:inspector:* — also fine
    ["my:custom:namespace:key"] = "value",

    -- No colon: avoid — ends up as "amazon:inspector:sbom_generator:custom_field"
    -- custom_field = "value",
}
```

### sbomgen에서 설정한 속성
<a name="sbomgen-plugin-api-reference-properties-set-by-sbomgen"></a>

 Sbomgen은 자체 속성을 내보내는 모든 구성 요소에 연결할 수 있습니다. 이러한 값은 예약된 `amazon:inspector:sbom_generator:*` 네임스페이스에서 가져온 것이므로 플러그인에서 생성해서는 안 됩니다. 관찰된 런타임 동작: 
+ `source_path`는 항상 sbomgen에 의해 추가됩니다.
+ `source_file_scanner` `source_package_collector`가 활성화되면 및 `--enable-debug-props`가 추가됩니다.

 예약 키의 전체 분류는 Amazon Inspector 사용 설명서: [ Amazon Inspector에서 CycloneDX 네임스페이스 사용에서](https://docs.aws.amazon.com/inspector/latest/user/cyclonedx-namespace.html) 유지됩니다.

## 속성 상수
<a name="sbomgen-plugin-api-reference-property-constants"></a>

 기본 제공 속성 키 상수는를 통해 사용할 수 있습니다`sbomgen.properties`. 아래의 모든 상수는 예약된 `amazon:inspector:sbom_generator:*` 네임스페이스 내의 키로 확인됩니다. 이러한 상수는 sbomgen의 내장 스캐너가 일관된 속성 키를 방출하도록 존재합니다. **사용자 지정 플러그인의 확장 지점이 아닙니다**. 사용자 지정 플러그인에서 이를 사용하면 Inspector가 의존하는 값을 섀도우로 지정할 수 있는 예약된 네임스페이스에 씁니다. 위의 섹션을 참조[예약 네임스페이스](#sbomgen-plugin-api-reference-reserved-namespaces)하세요.

 사용자 지정 플러그인 작성자는 이러한 상수를 재사용하는 대신 자체 네임스페이스(예: `acme:my_plugin:*`)에서 속성을 정의해야 합니다.


| **상수** | **해결된 값** | 
| --- | --- | 
| sbomgen.properties.NAMESPACE | amazon:inspector:sbom\_generator: | 
| sbomgen.properties.VENDOR | amazon:inspector:sbom\_generator:vendor | 
| sbomgen.properties.FILE\_SIZE\_BYTES | amazon:inspector:sbom\_generator:file\_size\_bytes | 
| sbomgen.properties.KERNEL\_COMPONENT | amazon:inspector:sbom\_generator:kernel\_component | 
| sbomgen.properties.RUNNING\_KERNEL | amazon:inspector:sbom\_generator:running\_kernel | 
| sbomgen.properties.UNRESOLVED\_VERSION | amazon:inspector:sbom\_generator:unresolved\_version | 
| sbomgen.properties.TRANSITIVE\_DEPENDENCY | amazon:inspector:sbom\_generator:experimental:transitive\_dependency | 
| sbomgen.properties.GO\_REPLACE\_DIRECTIVE | amazon:inspector:sbom\_generator:replaced\_by | 
| sbomgen.properties.DUPLICATE\_PACKAGE | amazon:inspector:sbom\_generator:is\_duplicate\_package | 
| sbomgen.properties.DUPLICATE\_PURL | amazon:inspector:sbom\_generator:duplicate\_purl | 
| sbomgen.properties.DOCKERFILE\_CHECK | amazon:inspector:sbom\_generator:dockerfile\_finding | 
| sbomgen.properties.CERTIFICATE\_FINDING | amazon:inspector:sbom\_generator:certificate\_finding | 
| sbomgen.properties.CERTIFICATE\_SUBJECT\_NAME | amazon:inspector:sbom\_generator:certificate:subject\_name | 
| sbomgen.properties.CERTIFICATE\_ISSUER\_NAME | amazon:inspector:sbom\_generator:certificate:issuer\_name | 
| sbomgen.properties.CERTIFICATE\_SIGNATURE\_ALGORITHM | amazon:inspector:sbom\_generator:certificate:signature\_algorithm | 
| sbomgen.properties.CERTIFICATE\_NOT\_VALID\_BEFORE | amazon:inspector:sbom\_generator:certificate:not\_valid\_before | 
| sbomgen.properties.CERTIFICATE\_NOT\_VALID\_AFTER | amazon:inspector:sbom\_generator:certificate:not\_valid\_after | 
| sbomgen.properties.WINDOWS\_REGISTRY\_KEY | amazon:inspector:sbom\_generator:registry\_key | 
| sbomgen.properties.SUBSCRIPTION\_ENABLED | amazon:inspector:sbom\_generator:subscription:enabled | 
| sbomgen.properties.SUBSCRIPTION\_NAME | amazon:inspector:sbom\_generator:subscription:name | 
| sbomgen.properties.SUBSCRIPTION\_LOCKED\_VERSION | amazon:inspector:sbom\_generator:subscription:locked\_version | 
| sbomgen.properties.OPENSSL\_FULL\_VERSION | amazon:inspector:sbom\_generator:openssl:full\_version | 
| sbomgen.properties.HARDENED\_IMAGE\_VENDOR | amazon:inspector:sbom\_generator:hardened\_image:vendor | 

## 스캐너 그룹
<a name="sbomgen-plugin-api-reference-scanner-groups"></a>

 검색 플러그인은를 통해 스캐너 그룹을 선언해야 합니다`get_scanner_groups()`. 그룹은 스캐너를 분류하고 사용자가 범주를 선택적으로 활성화하거나 비활성화할 수 있도록 허용합니다. 상수는를 통해 사용할 수 있습니다`sbomgen.groups`.


| **상수** | **값** | **설명** | 
| --- | --- | --- | 
| sbomgen.groups.OS | "os" | OS 패키지 관리자(dpkg, rpm 등) | 
| sbomgen.groups.PROGRAMMING\_LANGUAGE | "programming-language-packages" | 언어 패키지 관리자(pip, npm, maven 등) | 
| sbomgen.groups.BINARY | "binary" | 컴파일된 바이너리 분석(Go, Rust) | 
| sbomgen.groups.PACKAGE\_COLLECTOR | "pkg-scanner" | 일반 패키지 컬렉션 | 
| sbomgen.groups.EXTRA\_ECOSYSTEMS | "extra-ecosystems" | 추가 에코시스템(curl, nginx 등) | 
| sbomgen.groups.CERTIFICATE | "certificate" | 인증서 스캔 | 
| sbomgen.groups.CUSTOM | "custom" | 를 통해 로드된 모든 사용자 지정 플러그인에 자동으로 추가됨 --plugin-dir | 
| sbomgen.groups.MACHINE\_LEARNING | "machine-learning" | 기계 학습 모델 감지 | 

 예제: 

```
function get_scanner_groups()
    return {sbomgen.groups.PROGRAMMING_LANGUAGE, sbomgen.groups.PACKAGE_COLLECTOR}
end
```

## 구성 요소 유형 상수
<a name="sbomgen-plugin-api-reference-component-type-constants"></a>

 의 `component_type` 필드는 CycloneDX 1.5 구성 요소 유형 중 하나여야 `push_package()` 합니다. 상수는를 통해 사용할 수 있습니다`sbomgen.component_types`.


| **상수** | **값** | 
| --- | --- | 
| sbomgen.component\_types.APPLICATION | "application" | 
| sbomgen.component\_types.FRAMEWORK | "framework" | 
| sbomgen.component\_types.LIBRARY | "library" | 
| sbomgen.component\_types.CONTAINER | "container" | 
| sbomgen.component\_types.PLATFORM | "platform" | 
| sbomgen.component\_types.OPERATING\_SYSTEM | "operating-system" | 
| sbomgen.component\_types.DEVICE | "device" | 
| sbomgen.component\_types.DEVICE\_DRIVER | "device-driver" | 
| sbomgen.component\_types.FIRMWARE | "firmware" | 
| sbomgen.component\_types.FILE | "file" | 
| sbomgen.component\_types.MACHINE\_LEARNING\_MODEL | "machine-learning-model" | 
| sbomgen.component\_types.DATA | "data" | 

 예제: 

```
sbomgen.push_package({
    name = "requests",
    version = "2.28.1",
    purl_type = "pypi",
    component_type = sbomgen.component_types.LIBRARY,
})
```

## 플랫폼 상수
<a name="sbomgen-plugin-api-reference-platform-constants"></a>

 와 비교하기 위한 상수입니다`sbomgen.get_platform()`. 를 통해 사용 가능`sbomgen.platform`: 


| **상수** | **값** | 
| --- | --- | 
| sbomgen.platform.LINUX | "linux" | 
| sbomgen.platform.WINDOWS | "windows" | 
| sbomgen.platform.DARWIN | "darwin" | 

 예제: 

```
if sbomgen.get_platform() == sbomgen.platform.WINDOWS then
    -- Windows-specific logic
end
```

## 아티팩트 정보
<a name="sbomgen-plugin-api-reference-artifact-info"></a>

### `sbomgen.get_platform()`
<a name="sbomgen-plugin-api-reference-sbomgen-get-platform"></a>

 런타임 플랫폼 문자열(예: , `"linux"``"windows"`, `"darwin"`)을 반환합니다.

### `sbomgen.get_artifact_type()`
<a name="sbomgen-plugin-api-reference-sbomgen-get-artifact-type"></a>

 스캔 중인 아티팩트 유형(예: , `"directory"``"archive"`)을 반환합니다.

### `sbomgen.should_collect_licenses()`
<a name="sbomgen-plugin-api-reference-sbomgen-should-collect-licenses"></a>

 사용자가를 통해 라이선스 컬렉션을 활성화한 `true` 경우를 반환합니다`--collect-licenses`.

### `sbomgen.get_env_vars()`
<a name="sbomgen-plugin-api-reference-sbomgen-get-env-vars"></a>

 아티팩트의 환경 변수를 `{key, value}` 항목 테이블로 반환합니다.

```
local env_vars = sbomgen.get_env_vars()
for _, env in ipairs(env_vars) do
    if env.key == "NODE_ENV" then
        sbomgen.log_info("Node environment: " .. env.value)
    end
end
```

### `sbomgen.get_system_drive()`
<a name="sbomgen-plugin-api-reference-sbomgen-get-system-drive"></a>

 아티팩트의 환경에서 시스템 드라이브 문자(예: `"C:"`)를 반환합니다. `SystemDrive` 환경 변수를 읽으며 설정되지 않은 `"C:"` 경우 기본값은 입니다. 이는와 동등한 Lua입니다`strutils.GetSystemDriverLetter()`.

```
local drive = sbomgen.get_system_drive()
local program_files = drive .. "/Program Files/"
```

## 시스템 정보
<a name="sbomgen-plugin-api-reference-system-info"></a>

 이러한 함수는 아티팩트의 운영 체제 및 하드웨어에 대한 메타데이터를 반환합니다. 정보를 사용할 수 없는 경우(예: OS 메타데이터 없이 디렉터리를 스캔하는 경우) 값은 빈 문자열일 수 있습니다.


| **함수** | **반환** | 
| --- | --- | 
| sbomgen.get\_os\_name() | OS 이름(예: , "Ubuntu""Alpine Linux") | 
| sbomgen.get\_os\_version() | OS 버전(예: , "22.04""3.18") | 
| sbomgen.get\_os\_codename() | OS 코드 이름(예: , "jammy""bookworm") | 
| sbomgen.get\_os\_id() | OS 식별자(예: , "ubuntu""alpine") | 
| sbomgen.get\_kernel\_name() | 커널 이름(예: "Linux") | 
| sbomgen.get\_kernel\_version() | 커널 버전 문자열 | 
| sbomgen.get\_cpu\_arch() | CPU 아키텍처(예: , "x86\_64""aarch64") | 
| sbomgen.get\_hostname() | 시스템의 호스트 이름 | 

## 정규 표현식
<a name="sbomgen-plugin-api-reference-regular-expressions"></a>

 Lua의 기본 제공 패턴에는 대체(`|`), 한정자 범위(`{n,}`) 및 미리 보기와 같은 기능이 없습니다. 이 격차를 해소하기 위해 sbomgen은 Go의 `regexp` 패키지를 직접 노출합니다. 이러한 함수는 Lua 패턴이 아닌 Go 정규식 구문(RE2)을 사용합니다.

### `sbomgen.regex_find(str, pattern)`
<a name="sbomgen-plugin-api-reference-sbomgen-regex-find-str-pattern"></a>

 Go 정규식 패턴의 첫 번째 일치 항목을 반환하거나 일치하지 않는 `nil` 경우 반환합니다.
+ **다음을 반환합니다.** `string|nil, err` 

```
local version = sbomgen.regex_find(content, "\\d+\\.\\d+\\.\\d+")
```

### `sbomgen.regex_match(str, pattern)`
<a name="sbomgen-plugin-api-reference-sbomgen-regex-match-str-pattern"></a>

 첫 번째 매치에서 캡처 그룹을 반환합니다. 인덱스 1은 전체 일치 항목이고, 2\+는 캡처 그룹입니다.
+ **다음을 반환합니다.** `{string, ...}|nil, err` 

```
local groups = sbomgen.regex_match(content, "(MySQL|MariaDB) (\\d+)\\.(\\d+)\\.(\\d+)")
if groups then
    local db_type = groups[2]   -- "MySQL" or "MariaDB"
    local major   = groups[3]
end
```

### `sbomgen.regex_find_all(str, pattern [, n])`
<a name="sbomgen-plugin-api-reference-sbomgen-regex-find-all-str-pattern-n"></a>

 겹치지 않는 모든 일치 항목을 반환합니다. 결과를 제한`n`하도록 전달합니다(기본값: 모두).
+ **다음을 반환합니다.** `{string, ...}|nil, err` 

```
local versions = sbomgen.regex_find_all(content, "\\d+\\.\\d+\\.\\d+")
```

### `sbomgen.regex_replace(str, pattern, replacement)`
<a name="sbomgen-plugin-api-reference-sbomgen-regex-replace-str-pattern-replacement"></a>

 모든 일치 항목을 대체합니다. 대체 문자열은 캡처 그룹 참조에 `$1``$2`, 등을 사용할 수 있습니다.
+ **다음을 반환합니다.** `string, err` 

```
local cleaned = sbomgen.regex_replace(raw_version, "(1[6-9]\\d{8,}|buildkitsandbox.*)$", "")
```

### 정규식과 Lua 패턴을 사용해야 하는 경우
<a name="sbomgen-plugin-api-reference-when-to-use-regex-vs-lua-patterns"></a>

 간단한 패턴에는 Lua의 내장 `string.match`/`string.find`를 사용하세요. 더 빠르고 백슬래시를 이스케이프할 필요가 없습니다. 필요한 `sbomgen.regex_*` 경우를 사용합니다.
+ 대체: `(foo|bar)`
+ 양자 범위: `\d{8,}`
+ Lua 패턴으로 표현할 수 없는 복잡한 문자 클래스

## 구조화된 구문 분석
<a name="sbomgen-plugin-api-reference-structured-parsing"></a>

 Sbomgen은 구조화된 텍스트 형식을 Lua 테이블로 직접 디코딩하기 위한 경량 헬퍼를 노출합니다.

### `sbomgen.json_decode(str)`
<a name="sbomgen-plugin-api-reference-sbomgen-json-decode-str"></a>

 JSON 문자열을 Lua 테이블에 구문 분석합니다.
+ **다음을 반환합니다.** `table|nil, err` 

```
local doc, err = sbomgen.json_decode('{"name":"requests","version":"2.28.1"}')
if err then return end
sbomgen.log_info(doc.name)
```

### `sbomgen.xml_decode(str)`
<a name="sbomgen-plugin-api-reference-sbomgen-xml-decode-str"></a>

 XML 문자열을 Lua 테이블에 구문 분석합니다.
+ **다음을 반환합니다.** `table|nil, err` 

 XML 값은 다음 셰이프를 사용합니다.
+ `_name` - 요소 이름
+ `_attr` - 속성 테이블, 있는 경우
+ `_text` - 텍스트 콘텐츠가 있는 경우 잘라내기
+ 숫자 인덱스 `1..n` - 하위 요소

```
local doc, err = sbomgen.xml_decode('<package id="Newtonsoft.Json" version="13.0.3" />')
if err then return end
sbomgen.log_info(doc._attr.id)
```

## Windows 레지스트리
<a name="sbomgen-plugin-api-reference-windows-registry"></a>

 이러한 함수는 Windows 레지스트리에 대한 읽기 전용 액세스를 제공합니다. Windows가 아닌 아티팩트에서는 오류를 `registry_open_key` 반환합니다. 레지스트리 액세스 도구는 처음 사용할 때 느리게 초기화되며 라이브 Windows API 액세스(Windows의 로컬 호스트 스캔)와 파일 기반 REGF hive 구문 분석(컨테이너/볼륨 스캔)을 모두 지원합니다.

### `sbomgen.registry_open_key(path)`
<a name="sbomgen-plugin-api-reference-sbomgen-registry-open-key-path"></a>

 레지스트리 키를 엽니다. 로 닫아야 하는 키 핸들을 반환합니다`registry_close`.
+ **다음을 반환합니다.** `key, err` 

```
local key, err = sbomgen.registry_open_key("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\7-Zip")
if err then return end
-- use key...
sbomgen.registry_close(key)
```

### `sbomgen.registry_get_string(key, value_name)`
<a name="sbomgen-plugin-api-reference-sbomgen-registry-get-string-key-value-name"></a>

 열린 레지스트리 키에서 문자열 값을 읽습니다.
+ **다음을 반환합니다.** `string, err` 

```
local version, err = sbomgen.registry_get_string(key, "DisplayVersion")
```

### `sbomgen.registry_get_integer(key, value_name)`
<a name="sbomgen-plugin-api-reference-sbomgen-registry-get-integer-key-value-name"></a>

 열린 레지스트리 키에서 정수 값을 읽습니다.
+ **다음을 반환합니다.** `number, err` 

### `sbomgen.registry_get_strings(key, value_name)`
<a name="sbomgen-plugin-api-reference-sbomgen-registry-get-strings-key-value-name"></a>

 열린 레지스트리 키에서 다중 문자열(REG\_MULTI\_SZ) 값을 읽습니다. 문자열 테이블을 반환합니다.
+ **다음을 반환합니다.** `{string, ...}, err` 

```
local paths, err = sbomgen.registry_get_strings(key, "DependsOnService")
if paths then
    for _, p in ipairs(paths) do
        sbomgen.log_info("depends on: " .. p)
    end
end
```

### `sbomgen.registry_get_subkeys(key)`
<a name="sbomgen-plugin-api-reference-sbomgen-registry-get-subkeys-key"></a>

 열려 있는 레지스트리 키 아래에 있는 모든 하위 키 이름을 반환합니다.
+ **다음을 반환합니다.** `{string, ...}, err` 

```
local subkeys, err = sbomgen.registry_get_subkeys(key)
for _, name in ipairs(subkeys) do
    local subkey, err = sbomgen.registry_open_key(parent_path .. "\\" .. name)
    -- ...
end
```

### `sbomgen.registry_close(key)`
<a name="sbomgen-plugin-api-reference-sbomgen-registry-close-key"></a>

 레지스트리 키 핸들을 닫습니다. 키 핸들도 가비지 수집기에 의해 자동으로 닫히지만 명시적으로 닫는 것이 좋습니다.

## 로깅
<a name="sbomgen-plugin-api-reference-logging"></a>

 로그 메시지는 sbomgen의 콘솔 출력에 기록됩니다. 플러그인에서 내보내는 모든 메시지에는 플러그인의 소스 레이블 및 에코시스템 접두사가 자동으로 붙습니다. 예를 들면 다음과 같습니다.

```
[custom:python-pip] Parsing requirements.txt
```

 `log_info`, `log_warn`및는 `log_error` 항상 인쇄됩니다.는 sbomgen이 로 호출될 때`log_debug`만 인쇄됩니다`--verbose`.


| **함수** | **수준** | **기본적으로 표시됩니까?** | 
| --- | --- | --- | 
| sbomgen.log\_debug(message) | DEBUG | 아니요 -에 필요 --verbose | 
| sbomgen.log\_info(message) | INFO | 예 | 
| sbomgen.log\_warn(message) | WARN | 예 | 
| sbomgen.log\_error(message) | 오류 | 예 | 

 형식이 지정된 메시지`string.format`에를 사용합니다.

```
sbomgen.log_info(string.format("found %d packages in %s", count, file_path))
```

## 함수 디버깅
<a name="sbomgen-plugin-api-reference-debugging-functions"></a>

### `sbomgen.breakpoint(message)`
<a name="sbomgen-plugin-api-reference-sbomgen-breakpoint-message"></a>

 사용자가 Enter 키를 누`message`를 때까지 stderr로 인쇄하고 실행을 차단합니다. `message`이 생략되면가 기본 메시지를 인쇄합니다.

 플러그인의 키 포인트에 중단점을 배치하고 로 실행하여 주변 로그 출력을 `--verbose` 확인하여 이를 미정 디버거로 사용합니다.

```
sbomgen.log_info("state: " .. some_variable)
sbomgen.breakpoint("paused after state dump — press Enter to continue")
```

## API 테스트
<a name="sbomgen-plugin-api-reference-testing-api"></a>

 글로벌 `testing` 테이블 아래의 함수는에서 로드한 플러그인 테스트 파일(`*_test.lua`) 내에서만 사용할 수 있습니다`inspector-sbomgen plugin test`. 런타임에는 검색 또는 컬렉션 플러그인에서 사용할 수 없습니다. 전체 `sbomgen.*` API는 테스트 파일 내에서도 사용할 수 있지만 아티팩트(예: `sbomgen.read_file()`)가 필요한 `sbomgen.*` 함수는 스캔 내에서 호출될 때 의미 있는 결과만 생성합니다. 서술 가이드는 단원을 참조하십시오[플러그인 테스트 가이드](sbomgen-plugin-testing-guide.md).

### 스캔 함수
<a name="sbomgen-plugin-api-reference-scan-functions"></a>

 각 스캔 함수는 지정된 종류의 아티팩트를 생성하고, 해당 아티팩트에 대해 현재 플러그인의 검색 → 수집 파이프라인을 실행하고, 결과 결과를 반환합니다. `path` 인수는 테스트 파일의 디렉터리를 기준으로 확인됩니다.


| **함수** | **아티팩트 종류** | 
| --- | --- | 
| testing.scan\_directory(path) | 디렉터리 | 
| testing.scan\_archive(path) | 디렉터리(의 별칭scan\_directory) | 
| testing.scan\_localhost(path) | Localhost | 
| testing.scan\_binary(path) | 바이너리 | 
| testing.scan\_volume(path) | 볼륨 | 
| testing.scan\_container(path) | 컨테이너 | 

 6개 모두 아래 셰이프의 결과 테이블을 반환합니다.

### 결과 셰이프
<a name="sbomgen-plugin-api-reference-result-shape"></a>

 각 결과 테이블은 아래 나열된 필드만 프로젝션합니다. 특히 `namespace` 및 `purl_type`는 별도로 프로젝션되지 않으며 전체 `purl` 문자열에 통합됩니다.

```
local result = testing.scan_directory("_testdata/example")
-- result.findings                        -- array of finding tables
-- result.findings[i].name                -- string
-- result.findings[i].version             -- string
-- result.findings[i].component_type      -- string
-- result.findings[i].purl                -- string (the full Package URL, or "" if none)
-- result.findings[i].properties          -- table<string, string>
-- result.findings[i].children            -- array of finding tables (same shape, recursive)
```

### 어설션
<a name="sbomgen-plugin-api-reference-assertions"></a>


| **함수** | **Signature** | **설명** | 
| --- | --- | --- | 
| testing.assert\_equals | (expected: any, actual: any, message?: string) | 인 경우 실패합니다tostring(expected) \~= tostring(actual). | 
| testing.assert\_not\_equals | (expected: any, actual: any, message?: string) | 인 경우 실패합니다tostring(expected) == tostring(actual). | 
| testing.assert\_true | (value: any, message?: string) | 이 false 또는 value인 경우 실패합니다nil. | 
| testing.assert\_false | (value: any, message?: string) | value이 아닌 경우 실패false하고이 아닌 경우 실패합니다nil. | 
| testing.assert\_nil | (value: any, message?: string) | 이 value가 아닌 경우 실패합니다nil. | 
| testing.assert\_not\_nil | (value: any, message?: string) | 이 value인 경우 실패합니다nil. | 
| testing.assert\_contains | (haystack: string, needle: string, message?: string) | haystack에 needle (하위 문자열 일치)가 포함되어 있지 않으면 실패합니다. | 
| testing.assert\_matches | (str: string, pattern: string, message?: string) | str가 지정된 Go(RE2) 정규식과 일치하지 않으면 실패합니다. | 
| testing.assert\_length | (tbl: table, expected: integer, message?: string) | \#tbl가와 같지 않으면 실패합니다expected. | 

### 제어 흐름
<a name="sbomgen-plugin-api-reference-control-flow"></a>


| **함수** | **Signature** | **설명** | 
| --- | --- | --- | 
| testing.fail | (message: string) | 지정된 메시지와 함께 현재 테스트에 즉시 실패합니다. | 
| testing.skip | (message: string) | 현재 테스트를 건너뜁니다. 결과는 건너뛰고 실패하지 않은 것으로 보고됩니다. | 

### 테스트 검색
<a name="sbomgen-plugin-api-reference-test-discovery"></a>

 파일 일치`test_`에서 이름이 로 시작하는 모든 글로벌 Lua 함수`*_test.lua`는 테스트로 처리됩니다. 테스트 파일은 정상 `{phase}/{platform}/{category}/{ecosystem}/` 깊이`init.lua`에서 옆에 있어야 합니다. 수정 데이터는 테스트 파일 `_testdata/` 옆에 들어갑니다. 러너는 테스트 파일을 검색할 `_testdata/` 때 로 내림차순되지 않습니다.

## 오류 처리
<a name="sbomgen-plugin-api-reference-error-handling"></a>

 실패할 수 있는 API 함수는의 두 값을 반환합니다`value, err`. 성공 시 `err`는 입니다`nil`. 실패 시 첫 번째 값은 `nil` 이고 `err`는 오류 문자열입니다.

```
local content, err = sbomgen.read_file(path)
if err then
    sbomgen.log_error("failed to read " .. path .. ": " .. err)
    return
end
-- content is safe to use here
```

 플러그인에서 처리되지 않은 Lua 오류가 발생하면 sbomgen은 경고를 기록하고 다음 파일 또는 플러그인을 계속 진행합니다. 다른 플러그인은 영향을 받지 않습니다.