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

devonfw / IDEasy / 23045588121

13 Mar 2026 09:56AM UTC coverage: 70.384% (-0.2%) from 70.598%
23045588121

Pull #1742

github

web-flow
Merge 78b6ff13b into 6230b0284
Pull Request #1742: #1732: keep local changes when running ide update (git pull)

4141 of 6486 branches covered (63.85%)

Branch coverage included in aggregate %.

10746 of 14665 relevant lines covered (73.28%)

3.08 hits per line

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

40.37
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 org.slf4j.Logger;
11
import org.slf4j.LoggerFactory;
12

13
import com.devonfw.tools.ide.cli.CliException;
14
import com.devonfw.tools.ide.context.IdeContext;
15
import com.devonfw.tools.ide.log.IdeLogLevel;
16
import com.devonfw.tools.ide.os.SystemInfoImpl;
17
import com.devonfw.tools.ide.process.ProcessContext;
18
import com.devonfw.tools.ide.process.ProcessErrorHandling;
19
import com.devonfw.tools.ide.process.ProcessMode;
20
import com.devonfw.tools.ide.process.ProcessResult;
21
import com.devonfw.tools.ide.variable.IdeVariables;
22

23
/**
24
 * Implements the {@link GitContext}.
25
 */
26
public class GitContextImpl implements GitContext {
27

28
  private static final Logger LOG = LoggerFactory.getLogger(GitContextImpl.class);
4✔
29

30
  /** @see #getContext() */
31
  protected final IdeContext context;
32
  private Path git;
33

34
  /**
35
   * @param context the {@link IdeContext context}.
36
   */
37
  public GitContextImpl(IdeContext context) {
2✔
38

39
    this.context = context;
3✔
40
  }
1✔
41

42
  @Override
43
  public void pullOrCloneIfNeeded(GitUrl gitUrl, Path repository) {
44

45
    GitOperation.PULL_OR_CLONE.executeIfNeeded(this.context, gitUrl, repository, null);
8✔
46
  }
1✔
47

48
  @Override
49
  public boolean fetchIfNeeded(Path repository) {
50

51
    return fetchIfNeeded(repository, null, null);
×
52
  }
53

54
  @Override
55
  public boolean fetchIfNeeded(Path repository, String remote, String branch) {
56

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

60
  @Override
61
  public boolean isRepositoryUpdateAvailable(Path repository) {
62

63
    String localFailureMessage = String.format("Failed to get the local commit id of settings repository '%s'.", repository);
9✔
64
    String remoteFailureMessage = String.format("Failed to get the remote commit id of settings repository '%s', missing remote upstream branch?", repository);
9✔
65
    String localCommitId = runGitCommandAndGetSingleOutput(localFailureMessage, repository, ProcessMode.DEFAULT_CAPTURE, "rev-parse", "HEAD");
16✔
66
    String remoteCommitId = runGitCommandAndGetSingleOutput(remoteFailureMessage, repository, ProcessMode.DEFAULT_CAPTURE, "rev-parse", "@{u}");
16✔
67
    if ((localCommitId == null) || (remoteCommitId == null)) {
2!
68
      return false;
2✔
69
    }
70
    return !localCommitId.equals(remoteCommitId);
×
71
  }
72

73
  @Override
74
  public boolean isRepositoryUpdateAvailable(Path repository, Path trackedCommitIdPath) {
75

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

87
  @Override
88
  public void pullOrCloneAndResetIfNeeded(GitUrl gitUrl, Path repository, String remoteName) {
89

90
    pullOrCloneIfNeeded(gitUrl, repository);
4✔
91
    reset(repository, gitUrl.branch(), remoteName);
6✔
92
    cleanup(repository);
3✔
93
  }
1✔
94

95
  @Override
96
  public void pullSafelyWithStash(Path repository) {
97
    String token = "autostash:pull:" + java.util.UUID.randomUUID();
×
98
    LOG.debug("Untracked files found. Creating temporary stash with token '{}'", token);
×
99
    ProcessResult stashRes = runGitCommand(repository, ProcessMode.DEFAULT, "--no-pager", "stash", "push", "--include-untracked", "-m", token, "--quiet");
×
100
    if (!stashRes.isSuccessful()) {
×
101
      LOG.warn("Failed to create stash before pull on {}", repository);
×
102
      handleErrors(repository, stashRes);
×
103
    }
104

105
    ProcessResult listRes = runGitCommand(repository, ProcessMode.DEFAULT_CAPTURE, "--no-pager", "stash", "list");
×
106
    if (!listRes.isSuccessful()) {
×
107
      LOG.warn("Failed to list stash after creating temporary stash on {}", repository);
×
108
      handleErrors(repository, listRes);
×
109
    }
110

111
    String stashRef = findStashRefByMessage(listRes.getOut(), token);
×
112
    if (stashRef == null) {
×
113
      LOG.warn("Could not find created stash by token '{}'. Leaving stash untouched.", token);
×
114
    } else {
115
      LOG.debug("Created stash identified as '{}'", stashRef);
×
116
    }
117

118
    pull(repository);
×
119

120
    if (stashRef != null) {
×
121
      ProcessResult popRes = runGitCommand(repository, ProcessMode.DEFAULT, "--no-pager", "stash", "pop", stashRef, "--quiet");
×
122
      if (!popRes.isSuccessful()) {
×
123
        LOG.warn("Applying stash {} failed after successful pull on {}.", stashRef, repository);
×
124
        handleErrors(repository, popRes);
×
125
      } else {
126
        LOG.debug("Stash {} successfully popped after pull.", stashRef);
×
127
      }
128
    } else {
×
129
      LOG.warn("Skipping stash pop because stashRef is unknown (token '{}'). Stash remains on the stack.", token);
×
130
    }
131
  }
×
132

133
  @Override
134
  public boolean repoHasUntrackedFiles(Path repository) {
135
    ProcessResult status = runGitCommand(repository, ProcessMode.DEFAULT_CAPTURE, "--no-pager", "status", "--porcelain", "-uall");
×
136
    if (!status.isSuccessful()) {
×
137
      handleErrors(repository, status);
×
138
      return false;
×
139
    }
140
    List<String> out = status.getOut();
×
141
    return !out.isEmpty();
×
142
  }
143

144
  private String findStashRefByMessage(List<String> stashList, String needle) {
145
    if (stashList.isEmpty()) {
×
146
      return null;
×
147
    }
148
    for (String line : stashList) {
×
149
      if (line.contains(needle)) {
×
150
        int idx = line.indexOf(':');
×
151
        if (idx > 0) {
×
152
          return line.substring(0, idx).trim();
×
153
        }
154
      }
155
    }
×
156
    return null;
×
157
  }
158

159

160
  @Override
161
  public void pullOrClone(GitUrl gitUrl, Path repository) {
162

163
    Objects.requireNonNull(repository);
3✔
164
    Objects.requireNonNull(gitUrl);
3✔
165
    if (Files.isDirectory(repository.resolve(GIT_FOLDER))) {
7✔
166
      // checks for remotes
167
      String remote = determineRemote(repository);
4✔
168
      if (remote == null) {
2!
169
        String message = repository + " is a local git repository with no remote - if you did this for testing, you may continue...\n"
×
170
            + "Do you want to ignore the problem and continue anyhow?";
171
        this.context.askToContinue(message);
×
172
      } else {
×
173
        pull(repository);
3✔
174
      }
175
    } else {
1✔
176
      clone(gitUrl, repository);
4✔
177
    }
178
  }
1✔
179

180
  /**
181
   * Handles errors which occurred during git pull.
182
   *
183
   * @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
184
   *     git will by default create a sub-folder by default on clone but the * final folder that will contain the ".git" subfolder.
185
   * @param result the {@link ProcessResult} to evaluate.
186
   */
187
  private void handleErrors(Path targetRepository, ProcessResult result) {
188

189
    if (!result.isSuccessful()) {
×
190
      String message = "Failed to update git repository at " + targetRepository;
×
191
      if (this.context.isOfflineMode()) {
×
192
        LOG.warn(message);
×
193
        IdeLogLevel.INTERACTION.log(LOG, "Continuing as we are in offline mode - results may be outdated!");
×
194
      } else {
195
        LOG.error(message);
×
196
        if (this.context.isOnline()) {
×
197
          LOG.error("See above error for details. If you have local changes, please stash or revert and retry.");
×
198
        } else {
199
          LOG.error("It seems you are offline - please ensure Internet connectivity and retry or activate offline mode (-o or --offline).");
×
200
        }
201
        this.context.askToContinue("Typically you should abort and fix the problem. Do you want to continue anyways?");
×
202
      }
203
    }
204
  }
×
205

206
  @Override
207
  public void clone(GitUrl gitUrl, Path repository) {
208

209
    GitUrlSyntax gitUrlSyntax = IdeVariables.PREFERRED_GIT_PROTOCOL.get(getContext());
6✔
210
    gitUrl = gitUrlSyntax.format(gitUrl);
4✔
211
    if (this.context.isOfflineMode()) {
4✔
212
      this.context.requireOnline("git clone of " + gitUrl, false);
×
213
    }
214
    this.context.getFileAccess().mkdirs(repository);
5✔
215
    List<String> args = new ArrayList<>(7);
5✔
216
    args.add("clone");
4✔
217
    if (this.context.isQuietMode()) {
4!
218
      args.add("-q");
×
219
    }
220
    args.add("--recursive");
4✔
221
    args.add(gitUrl.url());
5✔
222
    args.add("--config");
4✔
223
    args.add("core.autocrlf=false");
4✔
224
    args.add(".");
4✔
225
    runGitCommand(repository, args);
4✔
226
    String branch = gitUrl.branch();
3✔
227
    if (branch != null) {
2!
228
      runGitCommand(repository, "switch", branch);
×
229
    }
230
  }
1✔
231

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

235
    if (this.context.isOffline()) {
4!
236
      LOG.info("Skipping git pull on {} because offline", repository);
×
237
      return;
×
238
    }
239
    ProcessResult result = runGitCommand(repository, ProcessMode.DEFAULT, "--no-pager", "pull", "--quiet");
19✔
240
    if (!result.isSuccessful()) {
3!
241
      String branchName = determineCurrentBranch(repository);
×
242
      LOG.warn("Git pull on branch {} failed for repository {}.", branchName, repository);
×
243
      handleErrors(repository, result);
×
244
    }
245
  }
1✔
246

247
  @Override
248
  public void fetch(Path repository, String remote, String branch) {
249

250
    if (branch == null) {
2!
251
      branch = determineCurrentBranch(repository);
×
252
    }
253
    if (remote == null) {
2!
254
      remote = determineRemote(repository);
×
255
    }
256

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

259
    if (!result.isSuccessful()) {
3!
260
      LOG.warn("Git fetch for '{}/{} failed.'.", remote, branch);
×
261
    }
262
  }
1✔
263

264
  @Override
265
  public String determineCurrentBranch(Path repository) {
266

267
    return runGitCommandAndGetSingleOutput("Failed to determine current branch of git repository", repository, "branch", "--show-current");
×
268
  }
269

270
  @Override
271
  public String determineRemote(Path repository) {
272

273
    return runGitCommandAndGetSingleOutput("Failed to determine current origin of git repository.", repository, "remote");
11✔
274
  }
275

276
  @Override
277
  public void reset(Path repository, String branchName, String remoteName) {
278

279
    if ((remoteName == null) || remoteName.isEmpty()) {
5!
280
      remoteName = DEFAULT_REMOTE;
2✔
281
    }
282
    if ((branchName == null) || branchName.isEmpty()) {
5!
283
      branchName = GitUrl.BRANCH_MASTER;
2✔
284
    }
285
    ProcessResult result = runGitCommand(repository, ProcessMode.DEFAULT, "diff-index", "--quiet", "HEAD");
19✔
286
    if (!result.isSuccessful()) {
3!
287
      // reset to origin/master
288
      LOG.warn("Git has detected modified files -- attempting to reset {} to '{}/{}'.", repository, remoteName, branchName);
17✔
289
      result = runGitCommand(repository, ProcessMode.DEFAULT, "reset", "--hard", remoteName + "/" + branchName);
21✔
290
      if (!result.isSuccessful()) {
3!
291
        LOG.warn("Git failed to reset {} to '{}/{}'.", remoteName, branchName, repository);
×
292
        handleErrors(repository, result);
×
293
      }
294
    }
295
  }
1✔
296

297
  @Override
298
  public void cleanup(Path repository) {
299

300
    // check for untracked files
301
    ProcessResult result = runGitCommand(repository, ProcessMode.DEFAULT_CAPTURE, "ls-files", "--other", "--directory", "--exclude-standard");
23✔
302
    if (!result.getOut().isEmpty()) {
4✔
303
      // delete untracked files
304
      LOG.warn("Git detected untracked files in {} and is attempting a cleanup.", repository);
4✔
305
      runGitCommand(repository, "clean", "-df");
13✔
306
    }
307
  }
1✔
308

309
  @Override
310
  public String retrieveGitUrl(Path repository) {
311

312
    return runGitCommandAndGetSingleOutput("Failed to retrieve git URL for repository", repository, "config", "--get", "remote.origin.url");
×
313
  }
314

315
  IdeContext getContext() {
316

317
    return this.context;
3✔
318
  }
319

320
  @Override
321
  public Path findGitRequired() {
322

323
    Path gitPath = findGit();
×
324
    if (gitPath == null) {
×
325
      String message = "Git " + IdeContext.IS_NOT_INSTALLED_BUT_REQUIRED;
×
326
      if (SystemInfoImpl.INSTANCE.isWindows()) {
×
327
        message += IdeContext.PLEASE_DOWNLOAD_AND_INSTALL_GIT + ":\n " + IdeContext.WINDOWS_GIT_DOWNLOAD_URL;
×
328
      }
329
      throw new CliException(message);
×
330
    }
331
    return gitPath;
×
332
  }
333

334
  @Override
335
  public Path findGit() {
336
    if (this.git != null) {
×
337
      return this.git;
×
338
    }
339

340
    Path gitPath = findGitInPath(Path.of("git"));
×
341

342
    if (gitPath == null) {
×
343
      if (SystemInfoImpl.INSTANCE.isWindows()) {
×
344
        gitPath = findGitOnWindowsViaBash();
×
345
      }
346
    }
347

348
    if (gitPath != null) {
×
349
      this.git = gitPath;
×
350
      LOG.trace("Found git at: {}", gitPath);
×
351
    }
352

353
    return gitPath;
×
354
  }
355

356
  private Path findGitOnWindowsViaBash() {
357
    Path gitPath;
358
    Path bashBinary = this.context.findBashRequired();
×
359
    LOG.trace("Trying to find git path on Windows");
×
360
    if (Files.exists(bashBinary)) {
×
361
      gitPath = bashBinary.getParent().resolve("git.exe");
×
362
      if (Files.exists(gitPath)) {
×
363
        LOG.trace("Git path was extracted from bash path at: {}", gitPath);
×
364
      } else {
365
        LOG.error("Git path: {} was extracted from bash path at: {} but it does not exist", gitPath, bashBinary);
×
366
        return null;
×
367
      }
368
    } else {
369
      LOG.error("Bash path was checked at: {} but it does not exist", bashBinary);
×
370
      return null;
×
371
    }
372
    return gitPath;
×
373
  }
374

375
  private Path findGitInPath(Path gitPath) {
376
    LOG.trace("Trying to find git executable within the PATH environment variable");
×
377
    Path binaryGitPath = this.context.getPath().findBinary(gitPath);
×
378
    if (gitPath == binaryGitPath) {
×
379
      LOG.debug("No git executable could be found within the PATH environment variable");
×
380
      return null;
×
381
    }
382
    return binaryGitPath;
×
383
  }
384

385
  private void runGitCommand(Path directory, String... args) {
386

387
    ProcessResult result = runGitCommand(directory, ProcessMode.DEFAULT, args);
6✔
388
    if (!result.isSuccessful()) {
3!
389
      String command = result.getCommand();
×
390
      this.context.requireOnline(command, false);
×
391
      result.failOnError();
×
392
    }
393
  }
1✔
394

395
  private void runGitCommand(Path directory, List<String> args) {
396

397
    runGitCommand(directory, args.toArray(String[]::new));
10✔
398
  }
1✔
399

400
  private String runGitCommandAndGetSingleOutput(String warningOnError, Path directory, String... args) {
401

402
    return runGitCommandAndGetSingleOutput(warningOnError, directory, ProcessMode.DEFAULT_CAPTURE, args);
7✔
403
  }
404

405
  private String runGitCommandAndGetSingleOutput(String warningOnError, Path directory, ProcessMode mode, String... args) {
406
    ProcessErrorHandling errorHandling = ProcessErrorHandling.NONE;
2✔
407
    if (LOG.isDebugEnabled()) {
3!
408
      errorHandling = ProcessErrorHandling.LOG_WARNING;
2✔
409
    }
410
    ProcessResult result = runGitCommand(directory, mode, errorHandling, args);
7✔
411
    if (result.isSuccessful()) {
3!
412
      List<String> out = result.getOut();
3✔
413
      int size = out.size();
3✔
414
      if (size == 1) {
3✔
415
        return out.getFirst();
4✔
416
      } else if (size == 0) {
2!
417
        warningOnError += " - No output received from " + result.getCommand();
6✔
418
      } else {
419
        warningOnError += " - Expected single line of output but received " + size + " lines from " + result.getCommand();
×
420
      }
421
    }
422
    LOG.warn(warningOnError);
3✔
423
    return null;
2✔
424
  }
425

426
  private ProcessResult runGitCommand(Path directory, ProcessMode mode, String... args) {
427

428
    return runGitCommand(directory, mode, ProcessErrorHandling.LOG_WARNING, args);
7✔
429
  }
430

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

433
    ProcessContext processContext;
434

435
    if (this.context.isBatchMode()) {
4!
436
      processContext = this.context.newProcess().executable(findGitRequired()).withEnvVar("GIT_TERMINAL_PROMPT", "0").withEnvVar("GCM_INTERACTIVE", "never")
×
437
          .withEnvVar("GIT_ASKPASS", "echo").withEnvVar("SSH_ASKPASS", "echo").errorHandling(errorHandling).directory(directory);
×
438
    } else {
439
      processContext = this.context.newProcess().executable(findGitRequired()).errorHandling(errorHandling).directory(directory);
11✔
440
    }
441

442
    processContext.addArgs(args);
4✔
443
    return processContext.run(mode);
4✔
444
  }
445

446
  @Override
447
  public void saveCurrentCommitId(Path repository, Path trackedCommitIdPath) {
448

449
    if ((repository == null) || (trackedCommitIdPath == null)) {
4!
450
      LOG.warn("Invalid usage of saveCurrentCommitId with null value");
×
451
      return;
×
452
    }
453
    LOG.trace("Saving commit Id of {} into {}", repository, trackedCommitIdPath);
5✔
454
    String currentCommitId = determineCurrentCommitId(repository);
4✔
455
    if (currentCommitId != null) {
2!
456
      try {
457
        Files.writeString(trackedCommitIdPath, currentCommitId);
6✔
458
      } catch (IOException e) {
×
459
        throw new IllegalStateException("Failed to save commit ID", e);
×
460
      }
1✔
461
    }
462
  }
1✔
463

464
  /**
465
   * @param repository the {@link Path} to the git repository.
466
   * @return the current commit ID of the given {@link Path repository}.
467
   */
468
  protected String determineCurrentCommitId(Path repository) {
469
    return runGitCommandAndGetSingleOutput("Failed to get current commit id.", repository, "rev-parse", FILE_HEAD);
×
470
  }
471
}
472

473

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