List of usage examples for org.eclipse.jgit.api Git add
public AddCommand add()
From source file:com.tenxdev.ovcs.command.AbstractSyncCommand.java
License:Open Source License
/** * Commit all changes and push to remote repository * * @throws OvcsException/*w w w . j ava 2s.c o m*/ * if changes could not be committed or pushed */ protected void commitAndPush() throws OvcsException { try { final FileRepository fileRepository = getRepoForCurrentDir(); final Git git = new Git(fileRepository); final Status status = git.status().setProgressMonitor(new TextProgressMonitor()).call(); if (!status.isClean()) { git.add().addFilepattern(".").call(); git.commit().setMessage("initial synchronization").setAll(true).call(); doPush(git); } } catch (final GitAPIException e) { throw new OvcsException("Unable to commit to git repo: " + e.getMessage(), e); } }
From source file:com.tenxdev.ovcs.command.CommitCommand.java
License:Open Source License
@Override /**/*from w w w . j a v a 2s .com*/ * {@inheritDoc} */ public void execute(final String... args) throws OvcsException { if (args.length != 1) { throw new OvcsException(USAGE); } System.out.println("Fetching changes from database..."); final FileRepository repository = getRepoForCurrentDir(); try { try (Connection conn = getDbConnectionForRepo(repository)) { final Git git = new Git(repository); final List<ChangeEntry> changes = writeChanges(repository); if (changes.isEmpty()) { System.out.println("No changes have been made, ending session"); } else { try { for (final ChangeEntry changeEntry : changes) { git.add() .addFilepattern(changeEntry.getName().toUpperCase(Locale.getDefault()) + ".sql") .call(); } git.commit().setMessage(getCommitMessage()).setAll(true).call(); } catch (final GitAPIException e) { throw new OvcsException("Unable to commit: " + e.getMessage(), e); } } try (CallableStatement stmt = conn.prepareCall("begin ovcs.handler.end_session; end;")) { stmt.execute(); conn.commit(); } catch (final SQLException e) { throw new OvcsException( "Unexpected error while committing database changes, you may have to call " + "ovcs.handler.end_session from your schema and commit to bring the database into a consistent state.", e); } if (!changes.isEmpty()) { try { doPush(git); System.out.println("All changes committed and sent to remote repository."); } catch (final GitAPIException e) { throw new OvcsException(String.format( "All changes have been committed, but were not sent to the remote repository%n" + "Please run the ovcs push command to retry sending to the remote repository%nError: %s", e.getMessage()), e); } } } catch (final SQLException e) { throw new OvcsException("Unexpected error while closing database connection, you may have to call " + "ovcs.handler.end_session from your schema and commit to bring the database into a consistent state.", e); } } finally { repository.close(); } }
From source file:com.uber.stream.kafka.mirrormaker.controller.core.GitBackUpHandler.java
License:Apache License
public void writeToFile(String fileName, String data) throws Exception { Repository backupRepo = null;/*from w w w . j a va 2 s. c o m*/ BufferedWriter output = null; Git git = null; Git result = null; try { try { FileUtils.deleteDirectory(new File(localPath)); } catch (IOException e) { LOGGER.error("Error deleting exisiting backup directory"); throw e; } try { result = Git.cloneRepository().setURI(remotePath).setDirectory(new File(localPath)).call(); } catch (Exception e) { LOGGER.error("Error cloning backup git repo"); throw e; } try { backupRepo = new FileRepository(localPath + "/.git"); } catch (IOException e) { throw e; } git = new Git(backupRepo); File myfile = new File(localPath + "/" + fileName); try { output = new BufferedWriter(new FileWriter(myfile)); output.write(data); output.flush(); } catch (IOException e) { LOGGER.error("Error writing backup to the file with name " + fileName); throw e; } try { git.add().addFilepattern(".").call(); } catch (GitAPIException e) { LOGGER.error("Error adding files to git"); throw e; } try { git.commit().setMessage("Taking backup on " + new Date()).call(); } catch (GitAPIException e) { LOGGER.error("Error commiting files to git"); throw e; } try { git.push().call(); } catch (GitAPIException e) { LOGGER.error("Error pushing files to git"); throw e; } } catch (Exception e) { throw e; } finally { output.close(); git.close(); if (result != null) result.getRepository().close(); backupRepo.close(); } }
From source file:com.wadpam.gimple.GimpleMojo.java
License:Open Source License
private RevCommit transformPomVersions(Git git, String newVersion) throws MojoExecutionException, GitAPIException { executeMojo(plugin("org.codehaus.mojo", "versions-maven-plugin", "2.1"), goal("set"), configuration(element(name("newVersion"), newVersion)), executionEnvironment(mavenProject, mavenSession, pluginManager)); StatusCommand statusCommand = git.status(); Status status = statusCommand.call(); // git add/* w w w .j av a 2 s . c o m*/ for (String uncommitted : status.getUncommittedChanges()) { getLog().info(" adding to git index: " + uncommitted); AddCommand add = git.add(); add.addFilepattern(uncommitted); add.call(); } // git commit CommitCommand commit = git.commit(); commit.setMessage(GIMPLE_MAVEN_PLUGIN + "pom version " + newVersion); return commit.call(); }
From source file:com.worldline.easycukes.scm.utils.GitHelper.java
License:Open Source License
/** * Adds all the files of the specified directory in the local git repository * (git add .), then commits the changes (git commit .), and finally pushes * the changes on the remote repository (git push) * * @param directory the directory in which the local git repository is located * @param username the username to be used while pushing * @param password the password matching with the provided username to be used * for authentication/*from w ww.j av a2s . c o m*/ * @param message the commit message to be used * @throws GitAPIException if something's going wrong while interacting with Git * @throws IOException if something's going wrong while manipulating the local * repository */ public static void commitAndPush(@NonNull File directory, String username, String password, String message) throws GitAPIException, IOException { try { final Git git = Git.open(directory); // run the add final AddCommand addCommand = git.add(); for (final String filePath : directory.list()) if (!".git".equals(filePath)) addCommand.addFilepattern(filePath); addCommand.call(); log.info("Added content of the directory" + directory + " in the Git repository located in " + directory.toString()); // and then commit final PersonIdent author = new PersonIdent(username, ""); git.commit().setCommitter(author).setMessage(message).setAuthor(author).call(); log.info("Commited the changes in the Git repository..."); // and finally push final UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider( username, password); git.push().setCredentialsProvider(userCredential).call(); log.info("Pushed the changes in remote Git repository..."); } catch (final GitAPIException e) { log.error(e.getMessage(), e); throw e; } }
From source file:de.blizzy.documentr.access.UserStore.java
License:Open Source License
/** * Saves a user.//from w w w .j a va 2 s. c om * * @param user the user to save * @param currentUser the user performing the save operation */ public void saveUser(User user, User currentUser) throws IOException { Assert.notNull(user); Assert.notNull(currentUser); ILockedRepository repo = null; try { repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false); Map<String, Object> userMap = new HashMap<String, Object>(); userMap.put("loginName", user.getLoginName()); //$NON-NLS-1$ userMap.put("password", user.getPassword()); //$NON-NLS-1$ userMap.put("email", user.getEmail()); //$NON-NLS-1$ userMap.put("disabled", Boolean.valueOf(user.isDisabled())); //$NON-NLS-1$ if (!user.getOpenIds().isEmpty()) { userMap.put("openIds", user.getOpenIds()); //$NON-NLS-1$ } Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); String json = gson.toJson(userMap); File workingDir = RepositoryUtil.getWorkingDir(repo.r()); File workingFile = new File(workingDir, user.getLoginName() + USER_SUFFIX); FileUtils.write(workingFile, json, Charsets.UTF_8); Git git = Git.wrap(repo.r()); git.add().addFilepattern(user.getLoginName() + USER_SUFFIX).call(); PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail()); git.commit().setAuthor(ident).setCommitter(ident).setMessage(user.getLoginName()).call(); } catch (GitAPIException e) { throw new IOException(e); } finally { Closeables.closeQuietly(repo); } }
From source file:de.blizzy.documentr.access.UserStore.java
License:Open Source License
/** * Saves a role.//from w w w . j ava 2 s . c om * * @param role the role to save * @param currentUser the user performing the save operation */ public void saveRole(Role role, User currentUser) throws IOException { Assert.notNull(role); Assert.notNull(currentUser); ILockedRepository repo = null; try { repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false); Map<String, Object> roleMap = new HashMap<String, Object>(); roleMap.put("name", role.getName()); //$NON-NLS-1$ Set<String> permissions = Sets.newHashSet(); for (Permission permission : role.getPermissions()) { permissions.add(permission.name()); } roleMap.put("permissions", permissions); //$NON-NLS-1$ Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); String json = gson.toJson(roleMap); File workingDir = RepositoryUtil.getWorkingDir(repo.r()); File workingFile = new File(workingDir, role.getName() + ROLE_SUFFIX); FileUtils.write(workingFile, json, Charsets.UTF_8); Git git = Git.wrap(repo.r()); git.add().addFilepattern(role.getName() + ROLE_SUFFIX).call(); PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail()); git.commit().setAuthor(ident).setCommitter(ident).setMessage(role.getName()).call(); } catch (GitAPIException e) { throw new IOException(e); } finally { Closeables.closeQuietly(repo); } }
From source file:de.blizzy.documentr.access.UserStore.java
License:Open Source License
private void saveUserAuthorities(String loginName, Set<RoleGrantedAuthority> authorities, ILockedRepository repo, User currentUser, boolean commit) throws IOException, GitAPIException { Map<String, Set<String>> authoritiesMap = new HashMap<String, Set<String>>(); for (RoleGrantedAuthority rga : authorities) { GrantedAuthorityTarget target = rga.getTarget(); String targetStr = target.getType().name() + ":" + target.getTargetId(); //$NON-NLS-1$ Set<String> roleNames = authoritiesMap.get(targetStr); if (roleNames == null) { roleNames = Sets.newHashSet(); authoritiesMap.put(targetStr, roleNames); }//from w w w . ja va2 s. com roleNames.add(rga.getRoleName()); } Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); String json = gson.toJson(authoritiesMap); File workingDir = RepositoryUtil.getWorkingDir(repo.r()); File workingFile = new File(workingDir, loginName + AUTHORITIES_SUFFIX); FileUtils.write(workingFile, json, Charsets.UTF_8); Git git = Git.wrap(repo.r()); git.add().addFilepattern(loginName + AUTHORITIES_SUFFIX).call(); if (commit) { PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail()); git.commit().setAuthor(ident).setCommitter(ident).setMessage(loginName).call(); } }
From source file:de.blizzy.documentr.access.UserStore.java
License:Open Source License
public void renameUser(String loginName, String newLoginName, User currentUser) throws IOException { Assert.hasLength(loginName);// w w w . j a v a 2 s . c om Assert.hasLength(newLoginName); Assert.notNull(currentUser); // check that user exists by trying to load it getUser(loginName); // check that new user does not exist by trying to load it try { getUser(newLoginName); throw new IllegalArgumentException("user already exists: " + newLoginName); //$NON-NLS-1$ } catch (UserNotFoundException e) { // okay } ILockedRepository repo = null; try { repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false); File workingDir = RepositoryUtil.getWorkingDir(repo.r()); File file = new File(workingDir, loginName + USER_SUFFIX); File newFile = new File(workingDir, newLoginName + USER_SUFFIX); FileUtils.copyFile(file, newFile); file = new File(workingDir, loginName + AUTHORITIES_SUFFIX); newFile = new File(workingDir, newLoginName + AUTHORITIES_SUFFIX); FileUtils.copyFile(file, newFile); Git git = Git.wrap(repo.r()); git.rm().addFilepattern(loginName + USER_SUFFIX).call(); git.rm().addFilepattern(loginName + AUTHORITIES_SUFFIX).call(); git.add().addFilepattern(newLoginName + USER_SUFFIX).call(); git.add().addFilepattern(newLoginName + AUTHORITIES_SUFFIX).call(); PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail()); git.commit().setAuthor(ident).setCommitter(ident) .setMessage("rename user " + loginName + " to " + newLoginName) //$NON-NLS-1$ //$NON-NLS-2$ .call(); } catch (GitAPIException e) { throw new IOException(e); } finally { Closeables.closeQuietly(repo); } }
From source file:de.blizzy.documentr.access.UserStore.java
License:Open Source License
public void renameRole(String roleName, String newRoleName, User currentUser) throws IOException { Assert.hasLength(roleName);//from w ww.j a va 2s .c o m Assert.hasLength(newRoleName); Assert.notNull(currentUser); // check that role exists by trying to load it getRole(roleName); // check that new role does not exist by trying to load it try { getRole(newRoleName); throw new IllegalArgumentException("role already exists: " + newRoleName); //$NON-NLS-1$ } catch (RoleNotFoundException e) { // okay } log.info("renaming role: {} -> {}", roleName, newRoleName); //$NON-NLS-1$ ILockedRepository repo = null; try { repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false); File workingDir = RepositoryUtil.getWorkingDir(repo.r()); File file = new File(workingDir, roleName + ROLE_SUFFIX); File newFile = new File(workingDir, newRoleName + ROLE_SUFFIX); FileUtils.copyFile(file, newFile); Git git = Git.wrap(repo.r()); git.rm().addFilepattern(roleName + ROLE_SUFFIX).call(); git.add().addFilepattern(newRoleName + ROLE_SUFFIX).call(); List<String> users = listUsers(repo); users.add(ANONYMOUS_USER_LOGIN_NAME); for (String user : users) { List<RoleGrantedAuthority> authorities = getUserAuthorities(user, repo); Set<RoleGrantedAuthority> newAuthorities = Sets.newHashSet(); for (Iterator<RoleGrantedAuthority> iter = authorities.iterator(); iter.hasNext();) { RoleGrantedAuthority rga = iter.next(); if (rga.getRoleName().equals(roleName)) { RoleGrantedAuthority newRga = new RoleGrantedAuthority(rga.getTarget(), newRoleName); newAuthorities.add(newRga); iter.remove(); } } if (!newAuthorities.isEmpty()) { authorities.addAll(newAuthorities); saveUserAuthorities(user, Sets.newHashSet(authorities), repo, currentUser, false); } } PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail()); git.commit().setAuthor(ident).setCommitter(ident) .setMessage("rename role " + roleName + " to " + newRoleName) //$NON-NLS-1$ //$NON-NLS-2$ .call(); } catch (GitAPIException e) { throw new IOException(e); } finally { Closeables.closeQuietly(repo); } }