Skip to content

[Duplicate Code] Port spec parsing loop duplicated for allowHostPorts and allowHostServicePorts #3812

@github-actions

Description

@github-actions

Duplicate Code Opportunity

Summary

  • Pattern: Comma-separated port spec parse-validate-collect loop
  • Locations: src/host-iptables-rules.ts lines 271–296 (two occurrences)
  • Impact: ~10 lines eliminated; validation logic stays consistent across both fields

Evidence

The two blocks in setupHostIptables() are nearly identical:

// Block 1 – allowHostPorts (lines 272–281)
if (hostAccess.allowHostPorts) {
  for (const entry of hostAccess.allowHostPorts.split(",")) {
    const trimmed = entry.trim();
    if (trimmed) {
      if (!isValidPortSpec(trimmed)) {
        logger.warn(`Skipping invalid port spec: ${trimmed}`);
        continue;
      }
      customPorts.push(trimmed);
    }
  }
}

// Block 2 – allowHostServicePorts (lines 287–296) – identical logic, different variable
if (hostAccess.allowHostServicePorts) {
  for (const entry of hostAccess.allowHostServicePorts.split(",")) {
    const trimmed = entry.trim();
    if (trimmed) {
      if (!isValidPortSpec(trimmed)) {
        logger.warn(`Skipping invalid host service port spec: ${trimmed}`);
        continue;
      }
      customPorts.push(trimmed);
    }
  }
}

The only difference is the source field and the warning message prefix — the validation logic is identical.

Suggested Refactoring

Extract a parseValidPortSpecs(input: string | undefined, label: string): string[] helper inside host-iptables-rules.ts (or src/parsers/host-port-parsers.ts):

function parseValidPortSpecs(input: string | undefined, label: string): string[] {
  if (!input) return [];
  const result: string[] = [];
  for (const entry of input.split(",")) {
    const trimmed = entry.trim();
    if (!trimmed) continue;
    if (!isValidPortSpec(trimmed)) {
      logger.warn(`Skipping invalid ${label}: ${trimmed}`);
      continue;
    }
    result.push(trimmed);
  }
  return result;
}

// Usage:
const customPorts = [
  ...parseValidPortSpecs(hostAccess.allowHostPorts, "port spec"),
  ...parseValidPortSpecs(hostAccess.allowHostServicePorts, "host service port spec"),
];

Affected Files

  • src/host-iptables-rules.ts — lines 270–296

Effort Estimate

Low


Detected by Duplicate Code Detector workflow. Run date: 2026-05-25

Generated by Duplicate Code Detector · sonnet46 3.6M ·

  • expires on Jun 24, 2026, 10:05 PM UTC

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions