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

devonfw / IDEasy / 16727716252

04 Aug 2025 03:42PM UTC coverage: 69.32% (+0.8%) from 68.562%
16727716252

push

github

web-flow
increase coverage (#1435)

Co-authored-by: juliane-cap <juliane.kostiuk@capgemini.com>

3332 of 5248 branches covered (63.49%)

Branch coverage included in aggregate %.

8614 of 11985 relevant lines covered (71.87%)

3.16 hits per line

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

61.78
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 localCommitId = runGitCommandAndGetSingleOutput("Failed to get the local commit id.", repository, "rev-parse", "HEAD");
15✔
57
    String remoteCommitId = runGitCommandAndGetSingleOutput("Failed to get the remote commit id.", repository, "rev-parse", "@{u}");
15✔
58
    if ((localCommitId == null) || (remoteCommitId == null)) {
2!
59
      return false;
2✔
60
    }
61
    return !localCommitId.equals(remoteCommitId);
×
62
  }
63

64
  @Override
65
  public boolean isRepositoryUpdateAvailable(Path repository, Path trackedCommitIdPath) {
66

67
    verifyGitInstalled();
×
68
    String trackedCommitId;
69
    try {
70
      trackedCommitId = Files.readString(trackedCommitIdPath);
×
71
    } catch (IOException e) {
×
72
      return false;
×
73
    }
×
74

75
    String remoteCommitId = runGitCommandAndGetSingleOutput("Failed to get the remote commit id.", repository, "rev-parse", "@{u}");
×
76
    return !trackedCommitId.equals(remoteCommitId);
×
77
  }
78

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

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

87
  @Override
88
  public void pullOrClone(GitUrl gitUrl, Path repository) {
89

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

107
  /**
108
   * Handles errors which occurred during git pull.
109
   *
110
   * @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
111
   *     git will by default create a sub-folder by default on clone but the * final folder that will contain the ".git" subfolder.
112
   * @param result the {@link ProcessResult} to evaluate.
113
   */
114
  private void handleErrors(Path targetRepository, ProcessResult result) {
115

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

133
  @Override
134
  public void clone(GitUrl gitUrl, Path repository) {
135

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

160
  @Override
161
  public void pull(Path repository) {
162

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

176
  @Override
177
  public void fetch(Path repository, String remote, String branch) {
178

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

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

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

194
  @Override
195
  public String determineCurrentBranch(Path repository) {
196

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

201
  @Override
202
  public String determineRemote(Path repository) {
203

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

208
  @Override
209
  public void reset(Path repository, String branchName, String remoteName) {
210

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

230
  @Override
231
  public void cleanup(Path repository) {
232

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

243
  @Override
244
  public String retrieveGitUrl(Path repository) {
245

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

250
  IdeContext getContext() {
251

252
    return this.context;
3✔
253
  }
254

255
  @Override
256
  public void verifyGitInstalled() {
257

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

269
  private void runGitCommand(Path directory, String... args) {
270

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

279
  private void runGitCommand(Path directory, List<String> args) {
280

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

284
  private String runGitCommandAndGetSingleOutput(String warningOnError, Path directory, String... args) {
285

286
    ProcessResult result = runGitCommand(directory, ProcessMode.DEFAULT_CAPTURE, args);
6✔
287
    if (result.isSuccessful()) {
3!
288
      List<String> out = result.getOut();
3✔
289
      int size = out.size();
3✔
290
      if (size == 1) {
3✔
291
        return out.get(0);
5✔
292
      } else if (size == 0) {
2!
293
        warningOnError += " - No output received from " + result.getCommand();
6✔
294
      } else {
295
        warningOnError += " - Expected single line of output but received " + size + " lines from " + result.getCommand();
×
296
      }
297
    }
298
    this.context.warning(warningOnError);
4✔
299
    return null;
2✔
300
  }
301

302
  private ProcessResult runGitCommand(Path directory, ProcessMode mode, String... args) {
303

304
    return runGitCommand(directory, mode, ProcessErrorHandling.LOG_WARNING, args);
7✔
305
  }
306

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

309
    ProcessContext processContext;
310

311
    if (this.context.isBatchMode()) {
4!
312
      processContext = this.context.newProcess().executable("git").withEnvVar("GIT_TERMINAL_PROMPT", "0").withEnvVar("GCM_INTERACTIVE", "never")
×
313
          .withEnvVar("GIT_ASKPASS", "echo").withEnvVar("SSH_ASKPASS", "echo").errorHandling(errorHandling).directory(directory);
×
314
    } else {
315
      processContext = this.context.newProcess().executable("git").errorHandling(errorHandling)
8✔
316
          .directory(directory);
2✔
317
    }
318

319
    processContext.addArgs(args);
4✔
320
    return processContext.run(mode);
4✔
321
  }
322

323
  @Override
324
  public void saveCurrentCommitId(Path repository, Path trackedCommitIdPath) {
325

326
    if ((repository == null) || (trackedCommitIdPath == null)) {
4!
327
      this.context.warning("Invalid usage of saveCurrentCommitId with null value");
×
328
      return;
×
329
    }
330
    this.context.trace("Saving commit Id of {} into {}", repository, trackedCommitIdPath);
14✔
331
    String currentCommitId = determineCurrentCommitId(repository);
4✔
332
    if (currentCommitId != null) {
2!
333
      try {
334
        Files.writeString(trackedCommitIdPath, currentCommitId);
6✔
335
      } catch (IOException e) {
×
336
        throw new IllegalStateException("Failed to save commit ID", e);
×
337
      }
1✔
338
    }
339
  }
1✔
340

341
  /**
342
   * @param repository the {@link Path} to the git repository.
343
   * @return the current commit ID of the given {@link Path repository}.
344
   */
345
  protected String determineCurrentCommitId(Path repository) {
346
    return runGitCommandAndGetSingleOutput("Failed to get current commit id.", repository, "rev-parse", FILE_HEAD);
×
347
  }
348
}
349

350

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

© 2026 Coveralls, Inc