1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @format
8 */
9
10'use strict';
11
12/**
13 * Try executing a function n times recursively.
14 * Return 0 the first time it succeeds
15 * Return code of the last failed commands if not more retries left
16 * @funcToRetry - function that gets retried
17 * @retriesLeft - number of retries to execute funcToRetry
18 * @onEveryError - func to execute if funcToRetry returns non 0
19 */
20function tryExecNTimes(funcToRetry, retriesLeft, onEveryError) {
21  const exitCode = funcToRetry();
22  if (exitCode === 0) {
23    return exitCode;
24  } else {
25    if (onEveryError) {
26      onEveryError();
27    }
28    retriesLeft--;
29    console.warn(`Command failed, ${retriesLeft} retries left`);
30    if (retriesLeft === 0) {
31      return exitCode;
32    } else {
33      return tryExecNTimes(funcToRetry, retriesLeft, onEveryError);
34    }
35  }
36}
37
38module.exports = tryExecNTimes;
39