Skip to content

feat: improve label print command with structured env vars and error logging#1529

Open
Trevor159 wants to merge 6 commits into
sysadminsmedia:mainfrom
Trevor159:better-label-command
Open

feat: improve label print command with structured env vars and error logging#1529
Trevor159 wants to merge 6 commits into
sysadminsmedia:mainfrom
Trevor159:better-label-command

Conversation

@Trevor159

@Trevor159 Trevor159 commented Jun 2, 2026

Copy link
Copy Markdown

What type of PR is this?

  • documentation
  • feature

Why we need it:

This PR builds on the current HBOX_LABEL_MAKER_PRINT_COMMAND configuration.

The feature has the following issues:

  1. The only documented template variable is {{.FileName}}, technically everything in
    if err := commandTemplate.Execute(builder, map[string]string{
    is supported.
  2. The variables for Name and description are inconsistent between assets and locations
  3. When the script errors the errors do not get propagated to the logs.
  4. Spaces in the template variables are not properly escaped so they are treated as multiple args to the script.
  5. There is not very much customization around users making their own label formats.

What this PR does

  • Adds more documentation around what I thought were the relevant variables that people might use in their scripts.
  • Adds new variables for name/description/asset_id that have consistent behavior across types.
  • Forwards errors from HBOX_LABEL_MAKER_PRINT_COMMAND to the logs
  • Adds all variables to the env of HBOX_LABEL_MAKER_PRINT_COMMAND which helpsr
  • with var parsing and fixes the space issue from above
  • Gives the user more context in their script so they can customize their labels more instead of using the provided label image. They can fit the labels to their label maker better this way if they want.
  • I made sure to not change any of the current label behavior so everything I touched is additive and shouldn't change any behavior for unaware users.

Special notes for your reviewer:

Anything I should add in the docs I added? Is there a way to see a preview of the doc website to make sure my links work?
Should I add parent locations to locations as well?

Testing

I tested this by building the docker container locally and configuring a print script. See the "these don't need to be in the PR" commit for my changes I used for local testing.

I have images with the python libraries needed for the brother ptouch label makers here that I am testing it with: https://github.com/Trevor159/homebox-brother-pt

@coderabbitai

coderabbitai Bot commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Summary by CodeRabbit

  • New Features

    • Enhanced label generation with structured metadata support (name, description, location, asset ID).
    • Custom label printing now supports template variables accessible as environment variables.
  • Documentation

    • Added comprehensive guide for custom label printing with available template variables and examples.
    • Updated environment variable documentation with reference to custom printing configuration options.

Walkthrough

Pass structured item metadata (Name, Description, Location, AssetID) from handlers into the labelmaker, include those fields in template rendering, expose them as LABEL_-prefixed environment variables to the print subprocess, and document the available variables for custom print commands.

Changes

Label Metadata Handling and Print Command Integration

Layer / File(s) Summary
Label Maker Parameter Contract Extension
backend/pkgs/labelmaker/labelmaker.go
Added exported ItemMetadata with Name, Description, Location, and AssetID. GenerateParameters embeds ItemMetadata. NewGenerateParams now accepts and assigns ItemMetadata.
Label Print Command Execution with Environment Variables
backend/pkgs/labelmaker/labelmaker.go
PrintLabel builds a templateVars map including metadata fields, renders templates, and constructs the subprocess environment by appending LABEL_<key>=<value> entries to os.Environ() before running the print command.
Handler Integration of Enriched Metadata
backend/app/api/handlers/v1/v1_ctrl_labelmaker.go
generateOrPrint signature changed to accept ItemMetadata. Location, Item, and Asset handlers extract parent/location/assetID and pass structured ItemMetadata (Name, Description, Location, AssetID) into label generation calls.
Documentation and Configuration Updates
docs/src/content/docs/en/user-guide/tips-tricks.mdx, docs/src/content/docs/en/quick-start/configure/index.mdx
Added "Custom Label Printing" section documenting HBOX_LABEL_MAKER_PRINT_COMMAND, supported Go template variables, and corresponding LABEL_ environment variables; updated quick-start to reference the new section.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • tankerkiller125
  • tonyaellie

Security Recommendations

  1. Validate and sanitize all metadata values (Name, Description, Location, AssetID) before rendering templates or exporting to environment variables to prevent injection or unexpected control characters.
  2. When the print command is invoked via a shell, ensure templates and env values cannot be interpreted as shell control sequences; prefer exec-style invocation without shell interpolation where possible.
  3. Document that HBOX_LABEL_MAKER_PRINT_COMMAND is user-configurable and must be configured safely; recommend quoting/escaping guidance and least-privilege subprocess execution.
  4. Ensure the subprocess runs with restricted privileges and has no access to unrelated sensitive environment or filesystem artifacts.

🏷️ Metadata flows through the label maker,
Template vars meet env—no data faker,
Print commands get context they need,
Enriched labels from items proceed! 🖨️

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main feature additions: structured environment variables for label printing and error logging improvements.
Description check ✅ Passed The description covers all required sections with clear problem statements, solutions, and testing approach, though it could be more detailed on error logging implementation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
✨ Simplify code
  • Create PR with simplified code

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot requested a review from tankerkiller125 June 2, 2026 23:11
@coderabbitai coderabbitai Bot added the 📖 documentation Improvements or additions to documentation label Jun 2, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
docs/src/content/docs/en/user-guide/tips-tricks.mdx (1)

79-97: ⚡ Quick win

Add a shell-safety warning and safe usage example for print command templates.

Because this runs via a shell command, interpolating metadata directly into the command string can lead to unsafe execution or broken arguments. Add a short caution to prefer reading values from LABEL_* env vars and always quote expansions in scripts.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/src/content/docs/en/user-guide/tips-tricks.mdx` around lines 79 - 97,
Add a short shell-safety caution to the HBOX_LABEL_MAKER_PRINT_COMMAND section
warning that template interpolation runs via a shell and can lead to unsafe
execution or broken arguments; recommend preferring the LABEL_* environment
variables (e.g., LABEL_URL, LABEL_Name, LABEL_AssetID) over inline template
expansion and explicitly instruct to always quote expansions in scripts. Also
add one brief, non-code safe-usage example description showing: pass values via
LABEL_* env vars to the print command and wrap expansions in quotes in the
script/command to avoid word-splitting and shell injection, referencing the
HBOX_LABEL_MAKER_PRINT_COMMAND setting and the supported template variables.
backend/pkgs/labelmaker/labelmaker.go (2)

73-92: 💤 Low value

Consider an options struct for cleaner API evolution.

The function signature has grown to 14 parameters, making call sites harder to read and prone to positional errors. For future extensibility, consider grouping the item-metadata fields into a dedicated struct (e.g., ItemMetadata{Name, Description, Location, AssetID}).

Not blocking for this PR, but worth considering for maintainability.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/pkgs/labelmaker/labelmaker.go` around lines 73 - 92, The
NewGenerateParams signature has become unwieldy; refactor by introducing a new
ItemMetadata struct (e.g., ItemMetadata with fields Name, Description, Location,
AssetID) and replace the four item-related string parameters in
NewGenerateParams with a single itemMetadata ItemMetadata parameter (or wrap all
optional parameters in an options struct) and update the returned
GenerateParameters construction to set Name, Description, Location, and AssetID
from that ItemMetadata; ensure callers are updated to build and pass
ItemMetadata and preserve AdditionalInformation, DynamicLength, and other
existing fields.

470-506: 💤 Low value

Security note: Item metadata now exposed to print subprocess.

The print command subprocess now receives potentially sensitive item data (names, descriptions, locations, asset IDs) via LABEL_* environment variables. This is the intended behavior per the PR, but worth documenting that:

  1. The print script (configured via HBOX_LABEL_MAKER_PRINT_COMMAND) has full access to label metadata
  2. Administrators should ensure print scripts handle this data appropriately, especially if logging or forwarding to external services

The implementation itself is secure—Go's exec.Cmd.Env properly isolates environment variable values from shell interpretation.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/pkgs/labelmaker/labelmaker.go` around lines 470 - 506, Add an
explicit security comment and admin guidance above the code that builds and sets
command.Env (around templateVars, env, and command.Env usage): state that the
print subprocess receives label metadata via LABEL_* environment variables
(e.g., Name, Description, Location, AssetID), reference the
HBOX_LABEL_MAKER_PRINT_COMMAND configuration, and advise administrators to
ensure their print scripts do not log, transmit, or mishandle sensitive item
data (or to sanitize/limit which fields are exported) and to restrict access to
the print command; keep the note concise and placed immediately before the env
loop/exec.Command usage.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docker-compose.yml`:
- Line 16: The docker-compose service currently sets the wrong and insecure
default debug environment variable: replace the HBOX_DEBUG=true entry with the
documented key HBOX_DEBUG_ENABLED and disable debug by default (e.g., set
HBOX_DEBUG_ENABLED=false or remove the boolean and use variable substitution
like ${HBOX_DEBUG_ENABLED:-false}) so consumers must opt-in to enable debug;
update any references to HBOX_DEBUG in startup scripts or README to use
HBOX_DEBUG_ENABLED to keep behavior consistent.

---

Nitpick comments:
In `@backend/pkgs/labelmaker/labelmaker.go`:
- Around line 73-92: The NewGenerateParams signature has become unwieldy;
refactor by introducing a new ItemMetadata struct (e.g., ItemMetadata with
fields Name, Description, Location, AssetID) and replace the four item-related
string parameters in NewGenerateParams with a single itemMetadata ItemMetadata
parameter (or wrap all optional parameters in an options struct) and update the
returned GenerateParameters construction to set Name, Description, Location, and
AssetID from that ItemMetadata; ensure callers are updated to build and pass
ItemMetadata and preserve AdditionalInformation, DynamicLength, and other
existing fields.
- Around line 470-506: Add an explicit security comment and admin guidance above
the code that builds and sets command.Env (around templateVars, env, and
command.Env usage): state that the print subprocess receives label metadata via
LABEL_* environment variables (e.g., Name, Description, Location, AssetID),
reference the HBOX_LABEL_MAKER_PRINT_COMMAND configuration, and advise
administrators to ensure their print scripts do not log, transmit, or mishandle
sensitive item data (or to sanitize/limit which fields are exported) and to
restrict access to the print command; keep the note concise and placed
immediately before the env loop/exec.Command usage.

In `@docs/src/content/docs/en/user-guide/tips-tricks.mdx`:
- Around line 79-97: Add a short shell-safety caution to the
HBOX_LABEL_MAKER_PRINT_COMMAND section warning that template interpolation runs
via a shell and can lead to unsafe execution or broken arguments; recommend
preferring the LABEL_* environment variables (e.g., LABEL_URL, LABEL_Name,
LABEL_AssetID) over inline template expansion and explicitly instruct to always
quote expansions in scripts. Also add one brief, non-code safe-usage example
description showing: pass values via LABEL_* env vars to the print command and
wrap expansions in quotes in the script/command to avoid word-splitting and
shell injection, referencing the HBOX_LABEL_MAKER_PRINT_COMMAND setting and the
supported template variables.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 63d90170-0300-4b63-9814-c5d2220fc158

📥 Commits

Reviewing files that changed from the base of the PR and between 139edf1 and a0d5716.

📒 Files selected for processing (5)
  • backend/app/api/handlers/v1/v1_ctrl_labelmaker.go
  • backend/pkgs/labelmaker/labelmaker.go
  • docker-compose.yml
  • docs/src/content/docs/en/quick-start/configure/index.mdx
  • docs/src/content/docs/en/user-guide/tips-tricks.mdx

Comment thread docker-compose.yml Outdated
@coderabbitai coderabbitai Bot requested a review from tonyaellie June 2, 2026 23:26

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
backend/app/api/handlers/v1/v1_ctrl_labelmaker.go (1)

46-61: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Swagger annotation produces image/png but declares @Produce json.

The handler returns a PNG image (via labelmaker.GenerateLabel) or plain text "Printed!", but the Swagger annotation at line 40 says @Produce json. This should be corrected for accurate API documentation.

📝 Suggested fix
 //	`@Summary`	Get Location label
 //	`@Tags`		Locations
-//	`@Produce`	json
+//	`@Produce`	png
 //	`@Param`		id		path		string	true	"Location ID"

Note: The same issue exists in HandleGetItemLabel (line 68) and HandleGetAssetLabel (line 104).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/api/handlers/v1/v1_ctrl_labelmaker.go` around lines 46 - 61, The
Swagger `@Produce` annotation is wrong: HandleGetLocationLabel (and similarly
HandleGetItemLabel and HandleGetAssetLabel) actually return a PNG image or plain
text "Printed!", so update the Swagger comments above these handler functions to
declare the correct MIME types (e.g. image/png and text/plain) instead of json;
ensure each function's comment block lists both image/png and text/plain so
generated docs match the actual responses.
backend/pkgs/labelmaker/labelmaker.go (2)

503-509: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Security consideration: Sanitize environment variable values to prevent injection.

Environment variable values are passed directly from user-controlled item metadata (Name, Description, Location, AssetID). While environment variables are generally safer than command-line arguments, values containing newlines or null bytes could cause unexpected behavior in some shells/scripts.

Consider sanitizing values by stripping or replacing control characters:

🛡️ Optional sanitization
+func sanitizeEnvValue(s string) string {
+	// Remove null bytes and replace newlines with spaces
+	s = strings.ReplaceAll(s, "\x00", "")
+	s = strings.ReplaceAll(s, "\n", " ")
+	s = strings.ReplaceAll(s, "\r", " ")
+	return s
+}
+
 env := os.Environ()
 for k, v := range templateVars {
-	env = append(env, "LABEL_"+k+"="+v)
+	env = append(env, "LABEL_"+k+"="+sanitizeEnvValue(v))
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/pkgs/labelmaker/labelmaker.go` around lines 503 - 509, Sanitize the
templateVars values before appending to env to prevent injection via control
characters (newlines, carriage returns, null bytes, other non-printables):
iterate over templateVars and replace or strip control characters from each v
before creating "LABEL_"+k+"="+v; update the code that builds env (the env
variable construction using templateVars) so only cleaned values are appended
and ensure command.Env (set on exec.Command) receives the sanitized env;
reference the templateVars map, the env slice, and command.Env when making the
change.

498-501: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Command parsing with strings.Fields can break quoted arguments containing spaces.

If the user's print command template expands to include values with spaces (e.g., {{.Name}} where Name is "Living Room"), strings.Fields splits on whitespace, turning one argument into multiple. This undermines the stated PR goal of "fix spaces-in-variables being treated as multiple script arguments."

The environment variable approach (lines 503-506) does provide a workaround since users can reference $LABEL_Name instead of {{.Name}}, but the template variable path remains broken for values with spaces.

💡 Suggested documentation or fix approach

Either:

  1. Document that template variables should only be used for the filename/URL (no spaces), and users should use $LABEL_* env vars for metadata with spaces, OR
  2. Consider shell-aware parsing (e.g., using a shell library or invoking via sh -c with the whole command as a single string):
-	commandParts := strings.Fields(builder.String())
-	if len(commandParts) == 0 {
-		return nil
-	}
-
-	env := os.Environ()
-	for k, v := range templateVars {
-		env = append(env, "LABEL_"+k+"="+v)
-	}
-
-	command := exec.Command(commandParts[0], commandParts[1:]...)
+	cmdStr := builder.String()
+	if strings.TrimSpace(cmdStr) == "" {
+		return nil
+	}
+
+	env := os.Environ()
+	for k, v := range templateVars {
+		env = append(env, "LABEL_"+k+"="+v)
+	}
+
+	command := exec.Command("sh", "-c", cmdStr)

Note: Using sh -c changes execution semantics and has its own security considerations if user-controlled values are interpolated into the command string.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/pkgs/labelmaker/labelmaker.go` around lines 498 - 501, The code
currently splits the expanded command via strings.Fields(builder.String()),
which breaks quoted arguments with spaces; update the command execution path in
the function that builds commandParts so it preserves quotes — either parse the
command string with a shell-aware parser (e.g., replace strings.Fields with a
POSIX word-splitting library such as shlex or mvdan's shell parser) to produce
correctly quoted arguments, or avoid splitting and invoke the command through
the shell (e.g., call sh -c with the full builder.String()) and document the
changed semantics/security tradeoffs; ensure references to builder.String(),
commandParts and the code path that sets env vars ($LABEL_*) are adjusted so
template-expanded values containing spaces are passed as single arguments.
🧹 Nitpick comments (2)
backend/pkgs/labelmaker/labelmaker.go (1)

488-492: 💤 Low value

Minor alignment inconsistency in templateVars map.

The new metadata fields (Name, Description, Location, AssetID) lack the tab alignment used by the preceding entries in the map literal. This is a cosmetic issue that doesn't affect functionality.

🔧 Suggested formatting fix
-		"Name":        params.Name,
-		"Description": params.Description,
-		"Location":    params.Location,
-		"AssetID":     params.AssetID,
+		"Name":                  params.Name,
+		"Description":           params.Description,
+		"Location":              params.Location,
+		"AssetID":               params.AssetID,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/pkgs/labelmaker/labelmaker.go` around lines 488 - 492, Align the tab
spacing of the new entries in the templateVars map so they match the existing
map literal alignment: adjust "Name": params.Name, "Description":
params.Description, "Location": params.Location, and "AssetID": params.AssetID
to use the same indentation/tabs as the preceding entries in the templateVars
map to maintain consistent formatting.
backend/app/api/handlers/v1/v1_ctrl_labelmaker.go (1)

87-96: 💤 Low value

Clarify the distinction between description (labelDesc) and ItemMetadata.Description.

The code correctly distinguishes between:

  • description (line 87-93): Text rendered ON the label showing location context ("Location: <parent>")
  • ItemMetadata.Description (line 96): The actual item's description field exposed as LABEL_Description env var

This aligns with the documentation table showing DescriptionText vs Description as separate concepts. However, a brief inline comment would help future maintainers understand this intentional distinction.

📝 Optional clarifying comment
-	description := ""
+	// labelDescription: text rendered ON the label (shows location context)
+	// ItemMetadata.Description: the item's actual description field for LABEL_Description env var
+	labelDescription := ""
 	parentName := ""

 	if item.Parent != nil {
 		parentName = item.Parent.Name
-		description += fmt.Sprintf("\nLocation: %s", parentName)
+		labelDescription += fmt.Sprintf("\nLocation: %s", parentName)
 	}

 	hbURL := GetHBURL(r, &ctrl.config.Options, ctrl.url)
-	return generateOrPrint(ctrl, w, r, item.Name, description, fmt.Sprintf("%s/item/%s", hbURL, item.ID), labelmaker.ItemMetadata{Name: item.Name, Description: item.Description, Location: parentName})
+	return generateOrPrint(ctrl, w, r, item.Name, labelDescription, fmt.Sprintf("%s/item/%s", hbURL, item.ID), labelmaker.ItemMetadata{Name: item.Name, Description: item.Description, Location: parentName})
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/api/handlers/v1/v1_ctrl_labelmaker.go` around lines 87 - 96, Add
a brief inline comment above the creation of the local variable description
(and/or above the generateOrPrint call) clarifying that the local variable
description (labelDesc) is the text rendered on the physical label (e.g.,
"Location: <parent>"), whereas labelmaker.ItemMetadata.Description (passed as
ItemMetadata.Description) is the item's actual description exposed as the
LABEL_Description env var; update the block around description, parentName,
GetHBURL and the generateOrPrint(...) call to include that comment so future
maintainers understand the intentional difference between the two values.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@backend/app/api/handlers/v1/v1_ctrl_labelmaker.go`:
- Around line 46-61: The Swagger `@Produce` annotation is wrong:
HandleGetLocationLabel (and similarly HandleGetItemLabel and
HandleGetAssetLabel) actually return a PNG image or plain text "Printed!", so
update the Swagger comments above these handler functions to declare the correct
MIME types (e.g. image/png and text/plain) instead of json; ensure each
function's comment block lists both image/png and text/plain so generated docs
match the actual responses.

In `@backend/pkgs/labelmaker/labelmaker.go`:
- Around line 503-509: Sanitize the templateVars values before appending to env
to prevent injection via control characters (newlines, carriage returns, null
bytes, other non-printables): iterate over templateVars and replace or strip
control characters from each v before creating "LABEL_"+k+"="+v; update the code
that builds env (the env variable construction using templateVars) so only
cleaned values are appended and ensure command.Env (set on exec.Command)
receives the sanitized env; reference the templateVars map, the env slice, and
command.Env when making the change.
- Around line 498-501: The code currently splits the expanded command via
strings.Fields(builder.String()), which breaks quoted arguments with spaces;
update the command execution path in the function that builds commandParts so it
preserves quotes — either parse the command string with a shell-aware parser
(e.g., replace strings.Fields with a POSIX word-splitting library such as shlex
or mvdan's shell parser) to produce correctly quoted arguments, or avoid
splitting and invoke the command through the shell (e.g., call sh -c with the
full builder.String()) and document the changed semantics/security tradeoffs;
ensure references to builder.String(), commandParts and the code path that sets
env vars ($LABEL_*) are adjusted so template-expanded values containing spaces
are passed as single arguments.

---

Nitpick comments:
In `@backend/app/api/handlers/v1/v1_ctrl_labelmaker.go`:
- Around line 87-96: Add a brief inline comment above the creation of the local
variable description (and/or above the generateOrPrint call) clarifying that the
local variable description (labelDesc) is the text rendered on the physical
label (e.g., "Location: <parent>"), whereas labelmaker.ItemMetadata.Description
(passed as ItemMetadata.Description) is the item's actual description exposed as
the LABEL_Description env var; update the block around description, parentName,
GetHBURL and the generateOrPrint(...) call to include that comment so future
maintainers understand the intentional difference between the two values.

In `@backend/pkgs/labelmaker/labelmaker.go`:
- Around line 488-492: Align the tab spacing of the new entries in the
templateVars map so they match the existing map literal alignment: adjust
"Name": params.Name, "Description": params.Description, "Location":
params.Location, and "AssetID": params.AssetID to use the same indentation/tabs
as the preceding entries in the templateVars map to maintain consistent
formatting.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: e2daee6b-cfd0-4f59-8965-8a728e2717d6

📥 Commits

Reviewing files that changed from the base of the PR and between a0d5716 and 73d2cfd.

📒 Files selected for processing (2)
  • backend/app/api/handlers/v1/v1_ctrl_labelmaker.go
  • backend/pkgs/labelmaker/labelmaker.go

@Trevor159 Trevor159 force-pushed the better-label-command branch from 73d2cfd to d35aec6 Compare June 13, 2026 17:01

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/pkgs/labelmaker/labelmaker.go (1)

473-492: ⚠️ Potential issue | 🟠 Major

Fix argv splitting for free-text template vars in HBOX_LABEL_MAKER_PRINT_COMMAND

Free-text template vars like Name, Description, Location (and other free-text fields) are inserted into the rendered command string, but the command is then split with strings.Fields, which ignores shell-style quoting—so values containing spaces/newlines get “chomped” into multiple argv entries (e.g. "Living Room Shelf" becomes ["\"Living","Room","Shelf\""]), making the template vars unreliable and changing the arguments passed to the external print program.

Security/robustness: build an argv slice directly from structured inputs, or switch to quote-aware parsing (e.g., shlex/shell-quote) instead of strings.Fields; otherwise restrict/document these fields as env-only.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/pkgs/labelmaker/labelmaker.go` around lines 473 - 492, The command
string built from templateVars (keys like "Name", "Description", "Location" in
the templateVars map) is being split with strings.Fields for
HBOX_LABEL_MAKER_PRINT_COMMAND which breaks quoted/free-text values with
spaces/newlines; fix by constructing the argv slice without strings.Fields:
either 1) build the []string explicitly from the structured inputs (use the
rendered program/args template to produce a slice of arguments and substitute
templateVars into each element) or 2) replace strings.Fields with a quote-aware
parser (shell-quote/shlex) so quoted values remain single argv entries; update
the code path that references HBOX_LABEL_MAKER_PRINT_COMMAND and remove the
strings.Fields call (or wrap it with the chosen shlex library) so templateVars
like Name/Description/Location are preserved as single arguments.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/pkgs/labelmaker/labelmaker.go`:
- Around line 511-514: The current failure path around command.CombinedOutput()
logs the entire child stdout/stderr (variables output and err); change this to
log only the exit error plus a redacted/capped excerpt of the combined output
instead of the full stream. Specifically, in the block handling output, capture
command.CombinedOutput() as before but when err != nil, create a short excerpt
(e.g., take the last N bytes or first N bytes, replace newlines with spaces, and
redact any LABEL_* tokens or other sensitive-looking patterns) and log a message
with err plus that capped/redacted excerpt; do not include the full output
variable in logs. Apply this change to the failure branch that currently prints
"label print command failed" so only the safer, capped excerpt is logged.

---

Outside diff comments:
In `@backend/pkgs/labelmaker/labelmaker.go`:
- Around line 473-492: The command string built from templateVars (keys like
"Name", "Description", "Location" in the templateVars map) is being split with
strings.Fields for HBOX_LABEL_MAKER_PRINT_COMMAND which breaks quoted/free-text
values with spaces/newlines; fix by constructing the argv slice without
strings.Fields: either 1) build the []string explicitly from the structured
inputs (use the rendered program/args template to produce a slice of arguments
and substitute templateVars into each element) or 2) replace strings.Fields with
a quote-aware parser (shell-quote/shlex) so quoted values remain single argv
entries; update the code path that references HBOX_LABEL_MAKER_PRINT_COMMAND and
remove the strings.Fields call (or wrap it with the chosen shlex library) so
templateVars like Name/Description/Location are preserved as single arguments.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 5768c51c-00ae-486b-94ae-4698d4942e3c

📥 Commits

Reviewing files that changed from the base of the PR and between 73d2cfd and d35aec6.

📒 Files selected for processing (4)
  • backend/app/api/handlers/v1/v1_ctrl_labelmaker.go
  • backend/pkgs/labelmaker/labelmaker.go
  • docs/src/content/docs/en/quick-start/configure/index.mdx
  • docs/src/content/docs/en/user-guide/tips-tricks.mdx
✅ Files skipped from review due to trivial changes (2)
  • docs/src/content/docs/en/quick-start/configure/index.mdx
  • docs/src/content/docs/en/user-guide/tips-tricks.mdx
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/app/api/handlers/v1/v1_ctrl_labelmaker.go

Comment on lines +511 to 514
output, err := command.CombinedOutput()
if err != nil {
log.Printf("label print command failed: %v\noutput: %s", err, string(output))
return err

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don’t log raw subprocess output verbatim.

This now persists the child’s full stdout/stderr into application logs on failure. Because the command inherits both the process environment and the new LABEL_* metadata, a failing script that dumps diagnostics can leak sensitive inventory data or credentials into logs. Prefer logging the exit error plus a capped/redacted stderr excerpt instead of the full combined stream.

Suggested direction
- output, err := command.CombinedOutput()
+ output, err := command.CombinedOutput()
  if err != nil {
- 	log.Printf("label print command failed: %v\noutput: %s", err, string(output))
+ 	const maxLogBytes = 4096
+ 	logOutput := string(output)
+ 	if len(logOutput) > maxLogBytes {
+ 		logOutput = logOutput[:maxLogBytes] + "…(truncated)"
+ 	}
+ 	log.Printf("label print command failed: %v; output: %q", err, logOutput)
  	return err
  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
output, err := command.CombinedOutput()
if err != nil {
log.Printf("label print command failed: %v\noutput: %s", err, string(output))
return err
output, err := command.CombinedOutput()
if err != nil {
const maxLogBytes = 4096
logOutput := string(output)
if len(logOutput) > maxLogBytes {
logOutput = logOutput[:maxLogBytes] + "…(truncated)"
}
log.Printf("label print command failed: %v; output: %q", err, logOutput)
return err
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/pkgs/labelmaker/labelmaker.go` around lines 511 - 514, The current
failure path around command.CombinedOutput() logs the entire child stdout/stderr
(variables output and err); change this to log only the exit error plus a
redacted/capped excerpt of the combined output instead of the full stream.
Specifically, in the block handling output, capture command.CombinedOutput() as
before but when err != nil, create a short excerpt (e.g., take the last N bytes
or first N bytes, replace newlines with spaces, and redact any LABEL_* tokens or
other sensitive-looking patterns) and log a message with err plus that
capped/redacted excerpt; do not include the full output variable in logs. Apply
this change to the failure branch that currently prints "label print command
failed" so only the safer, capped excerpt is logged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

📖 documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant