Java Code Examples for org.eclipse.jgit.api.Status#hasUncommittedChanges()

The following examples show how to use org.eclipse.jgit.api.Status#hasUncommittedChanges() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GitConfigurationPersister.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public String snapshot(String name, String comment) throws ConfigurationPersistenceException {
    boolean noComment = (comment ==null || comment.isEmpty());
    String message = noComment ? SNAPSHOT_PREFIX + FORMATTER.format(LocalDateTime.now()) : comment;
    String tagName = (name ==null || name.isEmpty()) ? SNAPSHOT_PREFIX + FORMATTER.format(LocalDateTime.now()) : name;
    try (Git git = gitRepository.getGit()) {
        Status status = git.status().call();
        List<Ref> tags = git.tagList().call();
        String refTagName = R_TAGS + tagName;
        for(Ref tag : tags) {
            if(refTagName.equals(tag.getName())) {
               throw MGMT_OP_LOGGER.snapshotAlreadyExistError(tagName);
            }
        }
        //if comment is not null
        if(status.hasUncommittedChanges() || !noComment) {
            git.commit().setMessage(message).setAll(true).setNoVerify(true).call();
        }
        git.tag().setName(tagName).setMessage(message).call();
    } catch (GitAPIException ex) {
        throw MGMT_OP_LOGGER.failedToPersistConfiguration(ex, message, ex.getMessage());
    }
    return message;
}
 
Example 2
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
public String commitFile(Repository repo, String site, String path, String comment, PersonIdent user) {
    String commitId = null;
    String gitPath = getGitPath(path);
    Status status;

    try (Git git = new Git(repo)) {
        status = git.status().addPath(gitPath).call();

        // TODO: SJ: Below needs more thought and refactoring to detect issues with git repo and report them
        if (status.hasUncommittedChanges() || !status.isClean()) {
            RevCommit commit;
            commit = git.commit().setOnly(gitPath).setAuthor(user).setCommitter(user).setMessage(comment).call();
            commitId = commit.getName();
        }

        git.close();
    } catch (GitAPIException e) {
        logger.error("error adding and committing file to git: site: " + site + " path: " + path, e);
    }

    return commitId;
}
 
Example 3
Source File: AbstractUpgradeOperation.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
protected void commitAllChanges(String site) throws UpgradeException {
    try {
        Path repositoryPath = getRepositoryPath(site);
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repo = builder
            .setGitDir(repositoryPath.toFile())
            .readEnvironment()
            .findGitDir()
            .build();

        try (Git git = new Git(repo)) {
            git.add().addFilepattern(".").call();

            Status status = git.status().call();

            if (status.hasUncommittedChanges() || !status.isClean()) {
                git.commit()
                    .setAll(true)
                    .setMessage(getCommitMessage())
                    .call();
            }
        }
    } catch (IOException | GitAPIException e) {
        throw new UpgradeException("Error committing changes for site " + site, e);
    }
}
 
Example 4
Source File: AvroGit.java    From metastore with Apache License 2.0 5 votes vote down vote up
@Override
protected void sync(ProtoDomain protoContainer, RegistryP.SubmitSchemaRequest.Comment comment)
    throws IOException {
  if (!config.isGitEnabled()) {
    return;
  }
  final Collection<Descriptors.Descriptor> descriptors =
      protoContainer.findDescriptorsByOption(rootOptionName);

  schemaFiles = new ArrayList<>();
  for (Descriptors.Descriptor descriptor : descriptors) {
    final String fileName = descriptor.getFullName();
    final String fullName = String.format("%s.avsc", fileName.replace(".", "/"));
    final String avroSchema = ProtoToAvroSchema.convert(protoContainer, fileName);
    schemaFiles.add(fullName);
    writeToFile(avroSchema, fullName, new File(config.getPath()).toPath().toString());
  }

  try (Scope scope = TRACER.spanBuilder("GitSync").setRecordEvents(true).startScopedSpan()) {
    if (System.getenv("DEBUG") != null && System.getenv("DEBUG").equals("true")) {
      return;
    }

    pull();
    gitRepo.add().addFilepattern(".").call();
    clean(protoContainer);

    Status status = gitRepo.status().call();
    if (status.hasUncommittedChanges()) {
      this.commit(comment);
      this.push();
      LOG.info("Git changes pushed");
    } else {
      LOG.info("No changes to commit");
    }
  } catch (Exception e) {
    throw new RuntimeException("Failed syncing the git repo", e);
  }
}
 
Example 5
Source File: MetaGit.java    From metastore with Apache License 2.0 5 votes vote down vote up
@Override
protected void sync(ProtoDomain protoContainer, Comment comment) {
  if (!config.isGitEnabled()) {
    return;
  }

  try (Scope scope = TRACER.spanBuilder("GitSync").setRecordEvents(true).startScopedSpan()) {
    if (System.getenv("DEBUG") != null && System.getenv("DEBUG").equals("true")) {
      protoContainer.writeToDirectory(new File(config.getPath()).toPath().toString());
      return;
    }

    pull();
    protoContainer.writeToDirectory(new File(config.getPath()).toPath().toString());
    gitRepo.add().addFilepattern(".").call();
    clean(protoContainer);
    Status status = gitRepo.status().call();
    if (status.hasUncommittedChanges()) {
      this.commit(comment);
      this.push();
      LOG.info("Git changes pushed");
    } else {
      LOG.info("No changes to commit");
    }
  } catch (Exception e) {
    throw new RuntimeException("Failed syncing the git repo", e);
  }
}
 
Example 6
Source File: GitFlowMetaData.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
boolean isGitDirectoryClean() throws GitAPIException {
    final Status status = new Git(gitRepo).status().call();
    return status.isClean() && !status.hasUncommittedChanges();
}
 
Example 7
Source File: Git.java    From docker-maven-plugin with Apache License 2.0 4 votes vote down vote up
public String getCommitId()
    throws GitAPIException, DockerException, IOException, MojoExecutionException {

  if (repo == null) {
    throw new MojoExecutionException(
        "Cannot tag with git commit ID because directory not a git repo");
  }

  final StringBuilder result = new StringBuilder();

  try {
    // get the first 7 characters of the latest commit
    final ObjectId head = repo.resolve("HEAD");
    if (head == null || isNullOrEmpty(head.getName())) {
      return null;
    }

    result.append(head.getName().substring(0, 7));
    final org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo);

    // append first git tag we find
    for (final Ref gitTag : git.tagList().call()) {
      if (gitTag.getObjectId().equals(head)) {
        // name is refs/tag/name, so get substring after last slash
        final String name = gitTag.getName();
        result.append(".");
        result.append(name.substring(name.lastIndexOf('/') + 1));
        break;
      }
    }

    // append '.DIRTY' if any files have been modified
    final Status status = git.status().call();
    if (status.hasUncommittedChanges()) {
      result.append(".DIRTY");
    }
  } finally {
    repo.close();
  }

  return result.length() == 0 ? null : result.toString();
}
 
Example 8
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * bootstrap the repository
 */
public void bootstrap() throws Exception {
    // Initialize the helper
    helper = new GitContentRepositoryHelper(studioConfiguration, servicesConfig, userServiceInternal,
            securityService);

    encryptor = new PbkAesTextEncryptor(studioConfiguration.getProperty(SECURITY_CIPHER_KEY),
            studioConfiguration.getProperty(SECURITY_CIPHER_SALT));

    if (Boolean.parseBoolean(studioConfiguration.getProperty(BOOTSTRAP_REPO)) && helper.createGlobalRepo()) {
        // Copy the global config defaults to the global site
        // Build a path to the bootstrap repo (the repo that ships with Studio)
        String bootstrapFolderPath = this.ctx.getRealPath(FILE_SEPARATOR + BOOTSTRAP_REPO_PATH +
                FILE_SEPARATOR + BOOTSTRAP_REPO_GLOBAL_PATH);
        Path source = java.nio.file.FileSystems.getDefault().getPath(bootstrapFolderPath);

        logger.info("Bootstrapping with baseline @ " + source.toFile().toString());

        // Copy the bootstrap repo to the global repo
        Path globalConfigPath = helper.buildRepoPath(GLOBAL);
        TreeCopier tc = new TreeCopier(source,
                globalConfigPath);
        EnumSet<FileVisitOption> opts = EnumSet.of(FOLLOW_LINKS);
        Files.walkFileTree(source, opts, MAX_VALUE, tc);

        String studioManifestLocation = this.ctx.getRealPath(STUDIO_MANIFEST_LOCATION);
        if (Files.exists(Paths.get(studioManifestLocation))) {
            FileUtils.copyFile(Paths.get(studioManifestLocation).toFile(),
                    Paths.get(globalConfigPath.toAbsolutePath().toString(),
                            studioConfiguration.getProperty(BLUE_PRINTS_PATH), "BLUEPRINTS.MF").toFile());
        }
        Repository globalConfigRepo = helper.getRepository(EMPTY, GLOBAL);
        try (Git git = new Git(globalConfigRepo)) {

            Status status = git.status().call();

            if (status.hasUncommittedChanges() || !status.isClean()) {
                // Commit everything
                // TODO: Consider what to do with the commitId in the future
                git.add().addFilepattern(GIT_COMMIT_ALL_ITEMS).call();
                git.commit().setMessage(helper.getCommitMessage(REPO_INITIAL_COMMIT_COMMIT_MESSAGE)).call();
            }

            git.close();
        } catch (GitAPIException err) {
            logger.error("error creating initial commit for global configuration", err);
        }
    }

    // Create global repository object
    if (!helper.buildGlobalRepo()) {
        logger.error("Failed to create global repository!");
    }
}
 
Example 9
Source File: RepositoryManagementServiceInternalImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean resolveConflict(String siteId, String path, String resolution)
        throws CryptoException, ServiceLayerException {
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration);
    Repository repo = helper.getRepository(siteId, SANDBOX);
    try (Git git = new Git(repo)) {
        switch (resolution.toLowerCase()) {
            case "ours" :
                logger.debug("Resolve conflict using OURS strategy for site " + siteId + " and path " + path);
                logger.debug("Reset merge conflict in git index");
                git.reset().addPath(helper.getGitPath(path)).call();
                logger.debug("Checkout content from HEAD of studio repository");
                git.checkout().addPath(helper.getGitPath(path)).setStartPoint(Constants.HEAD).call();
                break;
            case "theirs" :
                logger.debug("Resolve conflict using THEIRS strategy for site " + siteId + " and path " + path);
                logger.debug("Reset merge conflict in git index");
                git.reset().addPath(helper.getGitPath(path)).call();
                logger.debug("Checkout content from merge HEAD of remote repository");
                List<ObjectId> mergeHeads = repo.readMergeHeads();
                ObjectId mergeCommitId = mergeHeads.get(0);
                git.checkout().addPath(helper.getGitPath(path)).setStartPoint(mergeCommitId.getName()).call();
                break;
            default:
                throw new ServiceLayerException("Unsupported resolution strategy for repository conflicts");
        }

        if (repo.getRepositoryState() == RepositoryState.MERGING_RESOLVED) {
            logger.debug("Merge resolved. Check if there are no uncommitted changes (repo is clean)");
            Status status = git.status().call();
            if (!status.hasUncommittedChanges()) {
                logger.debug("Repository is clean. Committing to complete merge");
                String userName = securityService.getCurrentUser();
                User user = userServiceInternal.getUserByIdOrUsername(-1, userName);
                PersonIdent personIdent = helper.getAuthorIdent(user);
                git.commit()
                        .setAllowEmpty(true)
                        .setMessage("Merge resolved. Repo is clean (no changes)")
                        .setAuthor(personIdent)
                        .call();
            }
        }
    } catch (GitAPIException | IOException | UserNotFoundException | ServiceLayerException e) {
        logger.error("Error while resolving conflict for site " + siteId + " using " + resolution + " resolution " +
                "strategy", e);
        throw new ServiceLayerException("Error while resolving conflict for site " + siteId + " using " + resolution + " resolution " +
                "strategy", e);
    }
    return true;
}