• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

devonfw / IDEasy / 18588482774

17 Oct 2025 09:25AM UTC coverage: 68.437% (+0.02%) from 68.421%
18588482774

push

github

web-flow
#908: omit git error messages when retrieving status. (#1524)

Co-authored-by: Jörg Hohwiller <hohwille@users.noreply.github.com>
Co-authored-by: jan-vcapgemini <59438728+jan-vcapgemini@users.noreply.github.com>

3443 of 5513 branches covered (62.45%)

Branch coverage included in aggregate %.

9005 of 12676 relevant lines covered (71.04%)

3.12 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

62.39
cli/src/main/java/com/devonfw/tools/ide/git/GitContextImpl.java
1
package com.devonfw.tools.ide.git;
2

3
import java.io.IOException;
4
import java.nio.file.Files;
5
import java.nio.file.Path;
6
import java.util.ArrayList;
7
import java.util.List;
8
import java.util.Objects;
9

10
import com.devonfw.tools.ide.cli.CliException;
11
import com.devonfw.tools.ide.context.IdeContext;
12
import com.devonfw.tools.ide.process.ProcessContext;
13
import com.devonfw.tools.ide.process.ProcessErrorHandling;
14
import com.devonfw.tools.ide.process.ProcessMode;
15
import com.devonfw.tools.ide.process.ProcessResult;
16
import com.devonfw.tools.ide.variable.IdeVariables;
17

18
/**
19
 * Implements the {@link GitContext}.
20
 */
21
public class GitContextImpl implements GitContext {
22

23
  /** @see #getContext() */
24
  protected final IdeContext context;
25

26
  /**
27
   * @param context the {@link IdeContext context}.
28
   */
29
  public GitContextImpl(IdeContext context) {
2✔
30

31
    this.context = context;
3✔
32
  }
1✔
33

34
  @Override
35
  public void pullOrCloneIfNeeded(GitUrl gitUrl, Path repository) {
36

37
    GitOperation.PULL_OR_CLONE.executeIfNeeded(this.context, gitUrl, repository, null);
8✔
38
  }
1✔
39

40
  @Override
41
  public boolean fetchIfNeeded(Path repository) {
42

43
    return fetchIfNeeded(repository, null, null);
×
44
  }
45

46
  @Override
47
  public boolean fetchIfNeeded(Path repository, String remote, String branch) {
48

49
    return GitOperation.FETCH.executeIfNeeded(this.context, new GitUrl("https://dummy.url/repo.git", branch), repository, remote);
12✔
50
  }
51

52
  @Override
53
  public boolean isRepositoryUpdateAvailable(Path repository) {
54

55
    verifyGitInstalled();
2✔
56
    String localFailureMessage = String.format("Failed to get the local commit id of settings repository '%s'.",repository);
9✔
57
    String remoteFailureMessage = String.format("Failed to get the remote commit id of settings repository '%s', missing remote upstream branch?",repository);
9✔
58
    String localCommitId = runGitCommandAndGetSingleOutput(localFailureMessage, repository, ProcessMode.DEFAULT_CAPTURE, "rev-parse", "HEAD");
16✔
59
    String remoteCommitId = runGitCommandAndGetSingleOutput(remoteFailureMessage, repository, ProcessMode.DEFAULT_CAPTURE, "rev-parse", "@{u}");
16✔
60
    if ((localCommitId == null) || (remoteCommitId == null)) {
2!
61
      return false;
2✔
62
    }
63
    return !localCommitId.equals(remoteCommitId);
×
64
  }
65

66
  @Override
67
  public boolean isRepositoryUpdateAvailable(Path repository, Path trackedCommitIdPath) {
68

69
    verifyGitInstalled();
×
70
    String trackedCommitId;
71
    try {
72
      trackedCommitId = Files.readString(trackedCommitIdPath);
×
73
    } catch (IOException e) {
×
74
      return false;
×
75
    }
×
76
    String remoteFailureMessage = String.format("Failed to get the remote commit id of settings repository '%s', missing remote upstream branch?",repository);
×
77
    String remoteCommitId = runGitCommandAndGetSingleOutput(remoteFailureMessage, repository, ProcessMode.DEFAULT_CAPTURE, "rev-parse", "@{u}");
×
78
    return !trackedCommitId.equals(remoteCommitId);
×
79
  }
80

81
  @Override
82
  public void pullOrCloneAndResetIfNeeded(GitUrl gitUrl, Path repository, String remoteName) {
83

84
    pullOrCloneIfNeeded(gitUrl, repository);
4✔
85
    reset(repository, gitUrl.branch(), remoteName);
6✔
86
    cleanup(repository);
3✔
87
  }
1✔
88

89
  @Override
90
  public void pullOrClone(GitUrl gitUrl, Path repository) {
91

92
    Objects.requireNonNull(repository);
3✔
93
    Objects.requireNonNull(gitUrl);
3✔
94
    if (Files.isDirectory(repository.resolve(GIT_FOLDER))) {
7✔
95
      // checks for remotes
96
      String remote = determineRemote(repository);
4✔
97
      if (remote == null) {
2!
98
        String message = repository + " is a local git repository with no remote - if you did this for testing, you may continue...\n"
×
99
            + "Do you want to ignore the problem and continue anyhow?";
100
        this.context.askToContinue(message);
×
101
      } else {
×
102
        pull(repository);
3✔
103
      }
104
    } else {
1✔
105
      clone(gitUrl, repository);
4✔
106
    }
107
  }
1✔
108

109
  /**
110
   * Handles errors which occurred during git pull.
111
   *
112
   * @param targetRepository the {@link Path} to the target folder where the git repository should be cloned or pulled. It is not the parent directory where
113
   *     git will by default create a sub-folder by default on clone but the * final folder that will contain the ".git" subfolder.
114
   * @param result the {@link ProcessResult} to evaluate.
115
   */
116
  private void handleErrors(Path targetRepository, ProcessResult result) {
117

118
    if (!result.isSuccessful()) {
×
119
      String message = "Failed to update git repository at " + targetRepository;
×
120
      if (this.context.isOfflineMode()) {
×
121
        this.context.warning(message);
×
122
        this.context.interaction("Continuing as we are in offline mode - results may be outdated!");
×
123
      } else {
124
        this.context.error(message);
×
125
        if (this.context.isOnline()) {
×
126
          this.context.error("See above error for details. If you have local changes, please stash or revert and retry.");
×
127
        } else {
128
          this.context.error("It seems you are offline - please ensure Internet connectivity and retry or activate offline mode (-o or --offline).");
×
129
        }
130
        this.context.askToContinue("Typically you should abort and fix the problem. Do you want to continue anyways?");
×
131
      }
132
    }
133
  }
×
134

135
  @Override
136
  public void clone(GitUrl gitUrl, Path repository) {
137

138
    verifyGitInstalled();
2✔
139
    GitUrlSyntax gitUrlSyntax = IdeVariables.PREFERRED_GIT_PROTOCOL.get(getContext());
6✔
140
    gitUrl = gitUrlSyntax.format(gitUrl);
4✔
141
    if (this.context.isOfflineMode()) {
4✔
142
      this.context.requireOnline("git clone of " + gitUrl, false);
×
143
    }
144
    this.context.getFileAccess().mkdirs(repository);
5✔
145
    List<String> args = new ArrayList<>(7);
5✔
146
    args.add("clone");
4✔
147
    if (this.context.isQuietMode()) {
4!
148
      args.add("-q");
×
149
    }
150
    args.add("--recursive");
4✔
151
    args.add(gitUrl.url());
5✔
152
    args.add("--config");
4✔
153
    args.add("core.autocrlf=false");
4✔
154
    args.add(".");
4✔
155
    runGitCommand(repository, args);
4✔
156
    String branch = gitUrl.branch();
3✔
157
    if (branch != null) {
2!
158
      runGitCommand(repository, "switch", branch);
×
159
    }
160
  }
1✔
161

162
  @Override
163
  public void pull(Path repository) {
164

165
    verifyGitInstalled();
2✔
166
    if (this.context.isOffline()) {
4!
167
      this.context.info("Skipping git pull on {} because offline", repository);
×
168
      return;
×
169
    }
170
    ProcessResult result = runGitCommand(repository, ProcessMode.DEFAULT, "--no-pager", "pull", "--quiet");
19✔
171
    if (!result.isSuccessful()) {
3!
172
      String branchName = determineCurrentBranch(repository);
×
173
      this.context.warning("Git pull on branch {} failed for repository {}.", branchName, repository);
×
174
      handleErrors(repository, result);
×
175
    }
176
  }
1✔
177

178
  @Override
179
  public void fetch(Path repository, String remote, String branch) {
180

181
    verifyGitInstalled();
2✔
182
    if (branch == null) {
2!
183
      branch = determineCurrentBranch(repository);
×
184
    }
185
    if (remote == null) {
2!
186
      remote = determineRemote(repository);
×
187
    }
188

189
    ProcessResult result = runGitCommand(repository, ProcessMode.DEFAULT_CAPTURE, "fetch", Objects.requireNonNullElse(remote, "origin"), branch);
22✔
190

191
    if (!result.isSuccessful()) {
3!
192
      this.context.warning("Git fetch for '{}/{} failed.'.", remote, branch);
×
193
    }
194
  }
1✔
195

196
  @Override
197
  public String determineCurrentBranch(Path repository) {
198

199
    verifyGitInstalled();
×
200
    return runGitCommandAndGetSingleOutput("Failed to determine current branch of git repository", repository, "branch", "--show-current");
×
201
  }
202

203
  @Override
204
  public String determineRemote(Path repository) {
205

206
    verifyGitInstalled();
2✔
207
    return runGitCommandAndGetSingleOutput("Failed to determine current origin of git repository.", repository, "remote");
11✔
208
  }
209

210
  @Override
211
  public void reset(Path repository, String branchName, String remoteName) {
212

213
    verifyGitInstalled();
2✔
214
    if ((remoteName == null) || remoteName.isEmpty()) {
5!
215
      remoteName = DEFAULT_REMOTE;
2✔
216
    }
217
    if ((branchName == null) || branchName.isEmpty()) {
5!
218
      branchName = GitUrl.BRANCH_MASTER;
2✔
219
    }
220
    ProcessResult result = runGitCommand(repository, ProcessMode.DEFAULT, "diff-index", "--quiet", "HEAD");
19✔
221
    if (!result.isSuccessful()) {
3!
222
      // reset to origin/master
223
      this.context.warning("Git has detected modified files -- attempting to reset {} to '{}/{}'.", repository, remoteName, branchName);
18✔
224
      result = runGitCommand(repository, ProcessMode.DEFAULT, "reset", "--hard", remoteName + "/" + branchName);
21✔
225
      if (!result.isSuccessful()) {
3!
226
        this.context.warning("Git failed to reset {} to '{}/{}'.", remoteName, branchName, repository);
×
227
        handleErrors(repository, result);
×
228
      }
229
    }
230
  }
1✔
231

232
  @Override
233
  public void cleanup(Path repository) {
234

235
    verifyGitInstalled();
2✔
236
    // check for untracked files
237
    ProcessResult result = runGitCommand(repository, ProcessMode.DEFAULT_CAPTURE, "ls-files", "--other", "--directory", "--exclude-standard");
23✔
238
    if (!result.getOut().isEmpty()) {
4✔
239
      // delete untracked files
240
      this.context.warning("Git detected untracked files in {} and is attempting a cleanup.", repository);
10✔
241
      runGitCommand(repository, "clean", "-df");
13✔
242
    }
243
  }
1✔
244

245
  @Override
246
  public String retrieveGitUrl(Path repository) {
247

248
    verifyGitInstalled();
×
249
    return runGitCommandAndGetSingleOutput("Failed to retrieve git URL for repository", repository, "config", "--get", "remote.origin.url");
×
250
  }
251

252
  IdeContext getContext() {
253

254
    return this.context;
3✔
255
  }
256

257
  @Override
258
  public void verifyGitInstalled() {
259

260
    this.context.findBashRequired();
4✔
261
    Path git = Path.of("git");
5✔
262
    Path binaryGitPath = this.context.getPath().findBinary(git);
6✔
263
    if (git == binaryGitPath) {
3!
264
      String message = "Git is not installed on your computer but required by IDEasy. Please download and install git:\n"
×
265
          + "https://git-scm.com/download/";
266
      throw new CliException(message);
×
267
    }
268
    this.context.trace("Git is installed");
4✔
269
  }
1✔
270

271
  private void runGitCommand(Path directory, String... args) {
272

273
    ProcessResult result = runGitCommand(directory, ProcessMode.DEFAULT, args);
6✔
274
    if (!result.isSuccessful()) {
3!
275
      String command = result.getCommand();
×
276
      this.context.requireOnline(command, false);
×
277
      result.failOnError();
×
278
    }
279
  }
1✔
280

281
  private void runGitCommand(Path directory, List<String> args) {
282

283
    runGitCommand(directory, args.toArray(String[]::new));
10✔
284
  }
1✔
285

286
  private String runGitCommandAndGetSingleOutput(String warningOnError, Path directory, String... args) {
287

288
    return runGitCommandAndGetSingleOutput(warningOnError,directory, ProcessMode.DEFAULT_CAPTURE, args);
7✔
289
  }
290

291
  private String runGitCommandAndGetSingleOutput(String warningOnError, Path directory, ProcessMode mode, String... args) {
292
    ProcessErrorHandling errorHandling = ProcessErrorHandling.NONE;
2✔
293
    if (this.context.debug().isEnabled()){
5!
294
      errorHandling = ProcessErrorHandling.LOG_WARNING;
2✔
295
    }
296
    ProcessResult result = runGitCommand(directory, mode, errorHandling, args);
7✔
297
    if (result.isSuccessful()) {
3!
298
      List<String> out = result.getOut();
3✔
299
      int size = out.size();
3✔
300
      if (size == 1) {
3✔
301
        return out.get(0);
5✔
302
      } else if (size == 0) {
2!
303
        warningOnError += " - No output received from " + result.getCommand();
6✔
304
      } else {
305
        warningOnError += " - Expected single line of output but received " + size + " lines from " + result.getCommand();
×
306
      }
307
    }
308
    this.context.warning(warningOnError);
4✔
309
    return null;
2✔
310
  }
311

312
  private ProcessResult runGitCommand(Path directory, ProcessMode mode, String... args) {
313

314
    return runGitCommand(directory, mode, ProcessErrorHandling.LOG_WARNING, args);
7✔
315
  }
316

317
  private ProcessResult runGitCommand(Path directory, ProcessMode mode, ProcessErrorHandling errorHandling, String... args) {
318

319
    ProcessContext processContext;
320

321
    if (this.context.isBatchMode()) {
4!
322
      processContext = this.context.newProcess().executable("git").withEnvVar("GIT_TERMINAL_PROMPT", "0").withEnvVar("GCM_INTERACTIVE", "never")
×
323
          .withEnvVar("GIT_ASKPASS", "echo").withEnvVar("SSH_ASKPASS", "echo").errorHandling(errorHandling).directory(directory);
×
324
    } else {
325
      processContext = this.context.newProcess().executable("git").errorHandling(errorHandling)
8✔
326
          .directory(directory);
2✔
327
    }
328

329
    processContext.addArgs(args);
4✔
330
    return processContext.run(mode);
4✔
331
  }
332

333
  @Override
334
  public void saveCurrentCommitId(Path repository, Path trackedCommitIdPath) {
335

336
    if ((repository == null) || (trackedCommitIdPath == null)) {
4!
337
      this.context.warning("Invalid usage of saveCurrentCommitId with null value");
×
338
      return;
×
339
    }
340
    this.context.trace("Saving commit Id of {} into {}", repository, trackedCommitIdPath);
14✔
341
    String currentCommitId = determineCurrentCommitId(repository);
4✔
342
    if (currentCommitId != null) {
2!
343
      try {
344
        Files.writeString(trackedCommitIdPath, currentCommitId);
6✔
345
      } catch (IOException e) {
×
346
        throw new IllegalStateException("Failed to save commit ID", e);
×
347
      }
1✔
348
    }
349
  }
1✔
350

351
  /**
352
   * @param repository the {@link Path} to the git repository.
353
   * @return the current commit ID of the given {@link Path repository}.
354
   */
355
  protected String determineCurrentCommitId(Path repository) {
356
    return runGitCommandAndGetSingleOutput("Failed to get current commit id.", repository, "rev-parse", FILE_HEAD);
×
357
  }
358
}
359

360

STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc