Skip to content

Commit 8faf84a

Browse files
authored
fix: correct default branch detection and ensure consistent scanning behavior (#102)
FIXED BUGS: - Default branch detection was not working properly in git repositories - make_default_branch and set_as_pending_head were inconsistently set - CLI would skip scans when manifest files hadn't changed (should always scan) - --default-branch flag was being overridden by SCM detection - GitLab CI integration wasn't detecting default branch correctly CORRECTED BEHAVIOR: - Always perform scans regardless of manifest file changes (API mode when no manifests changed) - Proper default branch detection priority system: 1. Explicit --default-branch flag (highest priority) 2. CI environment variables (GitHub Actions, GitLab CI) 3. Git repository analysis via git_repo.is_default_branch 4. Fallback to false - Both make_default_branch and set_as_pending_head now synchronized correctly - Force API mode enables non-blocking behavior when no manifest files changed ENHANCED AUTO-DETECTION: - Repository name from git remote origin (was manual) - Branch, commit SHA, message, and committer from git (was manual) - Changed files from git commit (was manual) - Better error handling for non-git repositories SIMPLIFIED CI/CD USAGE: - Most parameters now optional due to git auto-detection - Added production-ready workflow examples: - workflows/github-actions.yml - GitHub Actions with concurrency control - workflows/gitlab-ci.yml - GitLab CI with environment detection - workflows/bitbucket-pipelines.yml - Bitbucket with path filtering - Updated README with corrected parameter documentation The CLI now works as users expected: - GitHub: socketcli --target-path --scm github --pr-number - GitLab: socketcli --target-path --scm gitlab --pr-number - Local: socketcli --target-path ./project
1 parent 69ec6b9 commit 8faf84a

File tree

9 files changed

+557
-71
lines changed

9 files changed

+557
-71
lines changed

README.md

Lines changed: 102 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,45 @@
11
# Socket Security CLI
22

3-
The Socket Security CLI was created to enable integrations with other tools like GitHub Actions, Gitlab, BitBucket, local use cases and more. The tool will get the head scan for the provided repo from Socket, create a new one, and then report any new alerts detected. If there are new alerts against the Socket security policy it'll exit with a non-Zero exit code.
3+
The Socket Security CLI was created to enable integrations with other tools like GitHub Actions, GitLab, BitBucket, local use cases and more. The tool will get the head scan for the provided repo from Socket, create a new one, and then report any new alerts detected. If there are new alerts against the Socket security policy it'll exit with a non-Zero exit code.
4+
5+
## Quick Start
6+
7+
The CLI now features automatic detection of git repository information, making it much simpler to use in CI/CD environments. Most parameters are now optional and will be detected automatically from your git repository.
8+
9+
### Minimal Usage Examples
10+
11+
**GitHub Actions:**
12+
```bash
13+
socketcli --target-path $GITHUB_WORKSPACE --scm github --pr-number $PR_NUMBER
14+
```
15+
16+
**GitLab CI:**
17+
```bash
18+
socketcli --target-path $CI_PROJECT_DIR --scm gitlab --pr-number ${CI_MERGE_REQUEST_IID:-0}
19+
```
20+
21+
**Local Development:**
22+
```bash
23+
socketcli --target-path ./my-project
24+
```
25+
26+
The CLI will automatically detect:
27+
- Repository name from git remote
28+
- Branch name from git
29+
- Commit SHA and message from git
30+
- Committer information from git
31+
- Default branch status from git and CI environment
32+
- Changed files from git commit history
33+
34+
## CI/CD Workflow Examples
35+
36+
Pre-configured workflow examples are available in the [`workflows/`](workflows/) directory:
37+
38+
- **[GitHub Actions](workflows/github-actions.yml)** - Complete workflow with concurrency control and automatic PR detection
39+
- **[GitLab CI](workflows/gitlab-ci.yml)** - Pipeline configuration with caching and environment variable handling
40+
- **[Bitbucket Pipelines](workflows/bitbucket-pipelines.yml)** - Basic pipeline setup with optional path filtering
41+
42+
These examples are production-ready and include best practices for each platform.
443

544
## Usage
645

@@ -25,36 +64,36 @@ If you don't want to provide the Socket API Token every time then you can use th
2564
#### Repository
2665
| Parameter | Required | Default | Description |
2766
|:-----------------|:---------|:--------|:------------------------------------------------------------------------|
28-
| --repo | False | | Repository name in owner/repo format |
67+
| --repo | False | *auto* | Repository name in owner/repo format (auto-detected from git remote) |
2968
| --integration | False | api | Integration type (api, github, gitlab) |
3069
| --owner | False | | Name of the integration owner, defaults to the socket organization slug |
31-
| --branch | False | "" | Branch name |
32-
| --committers | False | | Committer(s) to filter by |
70+
| --branch | False | *auto* | Branch name (auto-detected from git) |
71+
| --committers | False | *auto* | Committer(s) to filter by (auto-detected from git commit) |
3372
| --repo-is-public | False | False | If set, flags a new repository creation as public. Defaults to false. |
3473
3574
#### Pull Request and Commit
36-
| Parameter | Required | Default | Description |
37-
|:-----------------|:---------|:--------|:--------------------|
38-
| --pr-number | False | "0" | Pull request number |
39-
| --commit-message | False | | Commit message |
40-
| --commit-sha | False | "" | Commit SHA |
75+
| Parameter | Required | Default | Description |
76+
|:-----------------|:---------|:--------|:-----------------------------------------------|
77+
| --pr-number | False | "0" | Pull request number |
78+
| --commit-message | False | *auto* | Commit message (auto-detected from git) |
79+
| --commit-sha | False | *auto* | Commit SHA (auto-detected from git) |
4180
4281
#### Path and File
4382
| Parameter | Required | Default | Description |
4483
|:----------------------------|:---------|:----------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
4584
| --target-path | False | ./ | Target path for analysis |
4685
| --sbom-file | False | | SBOM file path |
47-
| --files | False | [] | Files to analyze (JSON array string) |
86+
| --files | False | *auto* | Files to analyze (JSON array string). Auto-detected from git commit changes when not specified |
4887
| --excluded-ecosystems | False | [] | List of ecosystems to exclude from analysis (JSON array string). You can get supported files from the [Supported Files API](https://docs.socket.dev/reference/getsupportedfiles) |
4988
| --license-file-name | False | `license_output.json` | Name of the file to save the license details to if enabled |
5089
| --save-submitted-files-list | False | | Save list of submitted file names to JSON file for debugging purposes |
5190
| --save-manifest-tar | False | | Save all manifest files to a compressed tar.gz archive with original directory structure |
5291
5392
#### Branch and Scan Configuration
54-
| Parameter | Required | Default | Description |
55-
|:-----------------|:---------|:--------|:------------------------------------------------------------|
56-
| --default-branch | False | False | Make this branch the default branch |
57-
| --pending-head | False | False | If true, the new scan will be set as the branch's head scan |
93+
| Parameter | Required | Default | Description |
94+
|:-----------------|:---------|:--------|:------------------------------------------------------------------------------------------------------|
95+
| --default-branch | False | *auto* | Make this branch the default branch (auto-detected from git and CI environment when not specified) |
96+
| --pending-head | False | *auto* | If true, the new scan will be set as the branch's head scan (automatically synced with default-branch) |
5897

5998
#### Output Configuration
6099
| Parameter | Required | Default | Description |
@@ -114,26 +153,66 @@ Example `SOCKET_SLACK_CONFIG_JSON` value
114153
{"url": "https://REPLACE_ME_WEBHOOK"}
115154
````
116155

156+
## Automatic Git Detection
157+
158+
The CLI now automatically detects repository information from your git environment, significantly simplifying usage in CI/CD pipelines:
159+
160+
### Auto-Detected Information
161+
162+
- **Repository name**: Extracted from git remote origin URL
163+
- **Branch name**: Current git branch or CI environment variables
164+
- **Commit SHA**: Latest commit hash or CI-provided commit SHA
165+
- **Commit message**: Latest commit message
166+
- **Committer information**: Git commit author details
167+
- **Default branch status**: Determined from git repository and CI environment
168+
- **Changed files**: Files modified in the current commit (for differential scanning)
169+
170+
### Default Branch Detection
171+
172+
The CLI uses intelligent default branch detection with the following priority:
173+
174+
1. **Explicit `--default-branch` flag**: Takes highest priority when specified
175+
2. **CI environment detection**: Uses CI platform variables (GitHub Actions, GitLab CI)
176+
3. **Git repository analysis**: Compares current branch with repository's default branch
177+
4. **Fallback**: Defaults to `false` if none of the above methods succeed
178+
179+
Both `--default-branch` and `--pending-head` parameters are automatically synchronized to ensure consistent behavior.
180+
181+
### Scan Behavior
182+
183+
The CLI determines scanning behavior intelligently:
184+
185+
- **Manifest files changed**: Performs differential scan with PR/MR comments when supported
186+
- **No manifest files changed**: Creates full repository scan report without waiting for diff results
187+
- **Force API mode**: When no supported manifest files are detected, automatically enables non-blocking mode
188+
117189
## File Selection Behavior
118190
119191
The CLI determines which files to scan based on the following logic:
120192
121-
1. **Git Commit Files**: By default, the CLI checks files changed in the current git commit first. If any of these files match supported manifest patterns (like package.json, requirements.txt, etc.), a scan is triggered.
193+
1. **Git Commit Files (Default)**: The CLI automatically checks files changed in the current git commit. If any of these files match supported manifest patterns (like package.json, requirements.txt, etc.), a scan is triggered.
194+
195+
2. **`--files` Parameter Override**: When specified, this parameter takes precedence over git commit detection. It accepts a JSON array of file paths to check for manifest files.
196+
197+
3. **`--ignore-commit-files` Flag**: When set, git commit files are ignored completely, and the CLI will scan all manifest files in the target directory regardless of what changed.
122198
123-
2. **`--files` Parameter**: If no git commit exists, or no manifest files are found in the commit changes, the CLI checks files specified via the `--files` parameter. This parameter accepts a JSON array of file paths.
199+
4. **Automatic Fallback**: If no manifest files are found in git commit changes and no `--files` are specified, the CLI automatically switches to "API mode" and performs a full repository scan.
124200
125-
3. **`--ignore-commit-files`**: When this flag is set, git commit files are ignored completely, and only files specified in `--files` are considered. This also forces a scan regardless of whether manifest files are present.
201+
> **Important**: The CLI doesn't scan only the specified files - it uses them to determine whether a scan should be performed and what type of scan to run. When triggered, it searches the entire `--target-path` for all supported manifest files.
126202

127-
4. **No Manifest Files**: If no manifest files are found in either git commit changes or `--files` (and `--ignore-commit-files` is not set), the scan is skipped.
203+
### Scanning Modes
128204

129-
> **Note**: The CLI does not scan only the specified files - it uses them to determine whether a scan should be performed. When a scan is triggered, it searches the entire `--target-path` for all supported manifest files.
205+
- **Differential Mode**: When manifest files are detected in changes, performs a diff scan with PR/MR comment integration
206+
- **API Mode**: When no manifest files are in changes, creates a full scan report without PR comments but still scans the entire repository
207+
- **Force Mode**: With `--ignore-commit-files`, always performs a full scan regardless of changes
130208

131209
### Examples
132210

133-
- **Commit with manifest file**: If your commit includes changes to `package.json`, a scan will be triggered automatically.
134-
- **Commit without manifest files**: If your commit only changes non-manifest files (like `.github/workflows/socket.yaml`), no scan will be performed unless you use `--files` or `--ignore-commit-files`.
135-
- **Using `--files`**: If you specify `--files '["package.json"]'`, the CLI will check if this file exists and is a manifest file before triggering a scan.
136-
- **Using `--ignore-commit-files`**: This forces a scan of all manifest files in the target path, regardless of what's in your commit.
211+
- **Commit with manifest file**: If your commit includes changes to `package.json`, a differential scan will be triggered automatically with PR comment integration.
212+
- **Commit without manifest files**: If your commit only changes non-manifest files (like `.github/workflows/socket.yaml`), the CLI automatically switches to API mode and performs a full repository scan.
213+
- **Using `--files`**: If you specify `--files '["package.json"]'`, the CLI will check if this file exists and is a manifest file before determining scan type.
214+
- **Using `--ignore-commit-files`**: This forces a full scan of all manifest files in the target path, regardless of what's in your commit.
215+
- **Auto-detection**: Most CI/CD scenarios now work with just `socketcli --target-path /path/to/repo --scm github --pr-number $PR_NUM`
137216
138217
## Debugging and Troubleshooting
139218

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
66

77
[project]
88
name = "socketsecurity"
9-
version = "2.1.23"
9+
version = "2.1.24"
1010
requires-python = ">= 3.10"
1111
license = {"file" = "LICENSE"}
1212
dependencies = [

socketsecurity/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
__author__ = 'socket.dev'
2-
__version__ = '2.1.23'
2+
__version__ = '2.1.24'

socketsecurity/core/__init__.py

Lines changed: 13 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -487,7 +487,7 @@ def create_full_scan_with_report_url(
487487
no_change: bool = False,
488488
save_files_list_path: str = None,
489489
save_manifest_tar_path: str = None
490-
) -> dict:
490+
) -> Diff:
491491
"""Create a new full scan and return with html_report_url.
492492
493493
Args:
@@ -501,12 +501,13 @@ def create_full_scan_with_report_url(
501501
Dict with full scan data including html_report_url
502502
"""
503503
log.debug(f"starting create_full_scan_with_report_url with no_change: {no_change}")
504+
diff = Diff(
505+
id="NO_SCAN_RAN",
506+
report_url="",
507+
diff_url=""
508+
)
504509
if no_change:
505-
return {
506-
"id": "NO_SCAN_RAN",
507-
"html_report_url": "",
508-
"unmatchedFiles": []
509-
}
510+
return diff
510511

511512
# Find manifest files
512513
files = self.find_files(path)
@@ -521,11 +522,7 @@ def create_full_scan_with_report_url(
521522

522523
files_for_sending = self.load_files_for_sending(files, path)
523524
if not files:
524-
return {
525-
"id": "NO_SCAN_RAN",
526-
"html_report_url": "",
527-
"unmatchedFiles": []
528-
}
525+
return diff
529526

530527
try:
531528
# Create new scan
@@ -539,25 +536,13 @@ def create_full_scan_with_report_url(
539536

540537
# Construct report URL
541538
base_socket = "https://socket.dev/dashboard/org"
542-
report_url = f"{base_socket}/{self.config.org_slug}/sbom/{new_full_scan.id}"
543-
if not params.include_license_details:
544-
report_url += "?include_license_details=false"
539+
diff.report_url = f"{base_socket}/{self.config.org_slug}/sbom/{new_full_scan.id}"
540+
diff.diff_url = diff.report_url
541+
diff.id = new_full_scan.id
542+
diff.packages = {}
545543

546544
# Return result in the format expected by the user
547-
return {
548-
"id": new_full_scan.id,
549-
"created_at": new_full_scan.created_at,
550-
"updated_at": new_full_scan.updated_at,
551-
"organization_id": new_full_scan.organization_id,
552-
"repository_id": new_full_scan.repository_id,
553-
"branch": new_full_scan.branch,
554-
"commit_message": new_full_scan.commit_message,
555-
"commit_hash": new_full_scan.commit_hash,
556-
"pull_request": new_full_scan.pull_request,
557-
"committers": new_full_scan.committers,
558-
"html_report_url": report_url,
559-
"unmatchedFiles": getattr(new_full_scan, 'unmatchedFiles', [])
560-
}
545+
return diff
561546

562547
def check_full_scans_status(self, head_full_scan_id: str, new_full_scan_id: str) -> bool:
563548
is_ready = False

0 commit comments

Comments
 (0)