All files / src/utils SafeDockerNetworkRemover.ts

100% Statements 10/10
85.71% Branches 6/7
100% Functions 3/3
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40    1x 1x                                 8x         1x         5x 5x 1x   4x 2x        
// SPDX-License-Identifier: Apache-2.0
 
import shell from 'shelljs';
import { IS_WINDOWS, NETWORK_PREFIX } from '../constants';
 
/**
 * Checks if the given string is a valid Docker network ID.
 * A valid Docker network ID is a 12-character hexadecimal string.
 *
 * @param {string} id - The string to be validated as a Docker network ID.
 * @returns {boolean} - Returns true if the string is a valid Docker network ID, false otherwise.
 *
 * @example
 * const id = "89ded1eca1d5";
 * console.log(isCorrectDockerId(id)); // Output: true
 *
 * @example
 * const invalidId = "invalidID123";
 * console.log(isCorrectDockerId(invalidId)); // Output: false
 */
const isCorrectDockerId = (id: string) => id.trim() !== '' && /^[a-f0-9]{12}$/.test(id);
 
/**
 * Provides utility methods for safe networks removal.
 */
export class SafeDockerNetworkRemover {
  /**
   * Removes all the networks started by docker compose. Only networks with the "hedera-" prefix will be affected.
   */
  public static removeAll() {
    const result = shell.exec(`docker network ls --filter name=${NETWORK_PREFIX} --format "{{.ID}}"`);
    if (!result || result.stderr !== '') {
      return;
    }
    result.stdout.split('\n').filter(isCorrectDockerId).forEach((id) => {
      shell.exec(`docker network rm ${id} -f 2>${IS_WINDOWS ? 'null' : '/dev/null'}`);
    });
  }
}