private void writeNewVersion(Document document) throws IOException, GitAPIException { final File docDir = getDirForDoc(document.getId()); Git git = null; if (!docDir.exists()) { docDir.mkdirs(); git = new InitCommand().setDirectory(docDir).call(); } else { git = Git.open(docDir); completeUndo(git); } File outputFile = new File(docDir, "document.xml"); FileOutputStream fos = new FileOutputStream(outputFile); try { document.serialize(fos); } catch (XMLStreamException e) { throw new RuntimeException(e); } finally { fos.close(); } git.add().addFilepattern("document.xml").call(); git.commit() .setCommitter("transmog", "*****@*****.**") .setMessage("Updated through application.") .call(); }
@Test public void testConflictsFromOtherPush() throws Exception { // now Repository 2 update the file and push File file1 = new File(workdir2, "file.txt"); repositoryUtil.appendFileContent(file1, "-->from Repository 2"); Git git = new Git(repository2); git.add().addFilepattern("file.txt").call(); git.commit().setMessage("Second Commit").call(); URIish remote = new URIish("file:///" + repository1.getDirectory().toString()); // now push the Repository 2 into the Repository 1 RefSpec rs = new RefSpec(); rs = rs.setSourceDestination("refs/heads/master", "refs/heads/master"); PushOperation po = new PushOperation(repository2, remote.toString(), Arrays.asList(rs), false, 0); po.execute(); System.out.println(po.toString()); // Now Repository 3 update the file and push File file2 = new File(workdir3, "file.txt"); repositoryUtil.appendFileContent(file2, "-->from Repository 3"); git = new Git(repository3); git.add().addFilepattern("file.txt").call(); git.commit().setMessage("Third Commit").call(); // now push the Repository 3 into the Repository 1 rs = new RefSpec(); rs = rs.setSourceDestination("refs/heads/master", "refs/heads/master"); // rs=rs.setForceUpdate(true); po = new PushOperation(repository3, remote.toString(), Arrays.asList(rs), false, 0); po.execute(); System.out.println(po.toString()); }
@Test public void testLinesAllDeletedShortenedWalk() throws Exception { Git git = new Git(db); String[] content1 = new String[] {"first", "second", "third"}; writeTrashFile("file.txt", join(content1)); git.add().addFilepattern("file.txt").call(); git.commit().setMessage("create file").call(); String[] content2 = new String[] {""}; writeTrashFile("file.txt", join(content2)); git.add().addFilepattern("file.txt").call(); git.commit().setMessage("create file").call(); writeTrashFile("file.txt", join(content1)); git.add().addFilepattern("file.txt").call(); RevCommit c3 = git.commit().setMessage("create file").call(); BlameGenerator generator = new BlameGenerator(db, "file.txt"); try { generator.push(null, db.resolve(Constants.HEAD)); assertEquals(3, generator.getResultContents().size()); assertTrue(generator.next()); assertEquals(c3, generator.getSourceCommit()); assertEquals(0, generator.getResultStart()); assertEquals(3, generator.getResultEnd()); assertFalse(generator.next()); } finally { generator.release(); } }
@Before public void setUp() throws Exception { sfb = new ZKServerFactoryBean(); delete(sfb.getDataDir()); delete(sfb.getDataLogDir()); sfb.afterPropertiesSet(); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() .connectString("localhost:" + sfb.getClientPortAddress().getPort()) .retryPolicy(new RetryOneTime(1000)) .connectionTimeoutMs(360000); curator = builder.build(); curator.start(); curator.getZookeeperClient().blockUntilConnectedOrTimedOut(); // setup a local and remote git repo basedir = System.getProperty("basedir", "."); File root = new File(basedir + "/target/git").getCanonicalFile(); delete(root); new File(root, "remote").mkdirs(); remote = Git.init().setDirectory(new File(root, "remote")).call(); remote.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call(); String remoteUrl = "file://" + new File(root, "remote").getCanonicalPath(); new File(root, "local").mkdirs(); git = Git.init().setDirectory(new File(root, "local")).call(); git.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call(); StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "origin", "url", remoteUrl); config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); config.save(); DefaultRuntimeProperties sysprops = new DefaultRuntimeProperties(); sysprops.setProperty(SystemProperties.KARAF_DATA, "target/data"); FabricGitServiceImpl gitService = new FabricGitServiceImpl(); gitService.bindRuntimeProperties(sysprops); gitService.activate(); gitService.setGitForTesting(git); DataStoreTemplateRegistry registrationHandler = new DataStoreTemplateRegistry(); registrationHandler.activateComponent(); dataStore = new CachingGitDataStore(); dataStore.bindCurator(curator); dataStore.bindGitService(gitService); dataStore.bindRegistrationHandler(registrationHandler); dataStore.bindRuntimeProperties(sysprops); dataStore.bindConfigurer( new Configurer() { @Override public <T> void configure(Map<String, ?> configuration, T target) throws Exception {} }); Map<String, String> datastoreProperties = new HashMap<String, String>(); datastoreProperties.put(GitDataStore.GIT_REMOTE_URL, remoteUrl); dataStore.activate(datastoreProperties); }
@Test public void testStageState_mergeAndReset_bug() throws Exception { try (Git git = new Git(db)) { writeTrashFile("a", "content"); git.add().addFilepattern("a").call(); RevCommit initialCommit = git.commit().setMessage("initial commit").call(); // create branch and add a new file final String branchName = Constants.R_HEADS + "branch"; createBranch(initialCommit, branchName); checkoutBranch(branchName); writeTrashFile("b", "second file content - branch"); git.add().addFilepattern("b").call(); RevCommit branchCommit = git.commit().setMessage("branch commit").call(); // checkout master and add the same new file checkoutBranch(Constants.R_HEADS + Constants.MASTER); writeTrashFile("b", "second file content - master"); git.add().addFilepattern("b").call(); git.commit().setMessage("master commit").call(); // try and merge MergeResult result = git.merge().include(branchCommit).call(); assertEquals(MergeStatus.CONFLICTING, result.getMergeStatus()); FileTreeIterator iterator = new FileTreeIterator(db); IndexDiff diff = new IndexDiff(db, Constants.HEAD, iterator); diff.diff(); assertTrue(diff.getChanged().isEmpty()); assertTrue(diff.getAdded().isEmpty()); assertTrue(diff.getRemoved().isEmpty()); assertTrue(diff.getMissing().isEmpty()); assertTrue(diff.getModified().isEmpty()); assertEquals(1, diff.getConflicting().size()); assertTrue(diff.getConflicting().contains("b")); assertEquals(StageState.BOTH_ADDED, diff.getConflictingStageStates().get("b")); assertTrue(diff.getUntrackedFolders().isEmpty()); // reset file b to its master state without altering the index writeTrashFile("b", "second file content - master"); // we should have the same result iterator = new FileTreeIterator(db); diff = new IndexDiff(db, Constants.HEAD, iterator); diff.diff(); assertTrue(diff.getChanged().isEmpty()); assertTrue(diff.getAdded().isEmpty()); assertTrue(diff.getRemoved().isEmpty()); assertTrue(diff.getMissing().isEmpty()); assertTrue(diff.getModified().isEmpty()); assertEquals(1, diff.getConflicting().size()); assertTrue(diff.getConflicting().contains("b")); assertEquals(StageState.BOTH_ADDED, diff.getConflictingStageStates().get("b")); assertTrue(diff.getUntrackedFolders().isEmpty()); } }
@Before public void setUp() throws Exception { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); FileUtils.mkdir(new File(root.getLocation().toFile(), "Sub"), true); gitDir = new File(new File(root.getLocation().toFile(), "Sub"), Constants.DOT_GIT); repository = FileRepositoryBuilder.create(gitDir); repository.create(); project = root.getProject(TEST_PROJECT); project.create(null); project.open(null); IProjectDescription description = project.getDescription(); description.setLocation(root.getLocation().append(TEST_PROJECT_LOC)); project.move(description, IResource.FORCE, null); project2 = root.getProject(TEST_PROJECT2); project2.create(null); project2.open(null); gitDir2 = new File(project2.getLocation().toFile().getAbsoluteFile(), Constants.DOT_GIT); repository2 = FileRepositoryBuilder.create(gitDir2); repository2.create(); RepositoryMapping mapping = RepositoryMapping.create(project, gitDir); RepositoryMapping mapping2 = RepositoryMapping.create(project2, gitDir2); GitProjectData projectData = new GitProjectData(project); GitProjectData projectData2 = new GitProjectData(project2); projectData.setRepositoryMappings(Collections.singletonList(mapping)); projectData.store(); projectData2.setRepositoryMappings(Collections.singletonList(mapping2)); projectData2.store(); GitProjectData.add(project, projectData); GitProjectData.add(project2, projectData2); RepositoryProvider.map(project, GitProvider.class.getName()); RepositoryProvider.map(project2, GitProvider.class.getName()); JGitTestUtil.write( new File(repository.getWorkTree(), TEST_PROJECT + "/" + TEST_FILE), "Some data"); JGitTestUtil.write(new File(repository2.getWorkTree(), TEST_FILE2), "Some other data"); project.refreshLocal(IResource.DEPTH_INFINITE, null); project2.refreshLocal(IResource.DEPTH_INFINITE, null); git = new Git(repository); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git = new Git(repository2); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.branchRename().setNewName("main").call(); }
@Test public void testPushToNonBareRepository() throws Exception { CloneCommand clone = Git.cloneRepository(); clone.setURI(MessageFormat.format("{0}/git/working/jgit", url)); clone.setDirectory(jgit2Folder); clone.setBare(false); clone.setCloneAllBranches(true); clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password)); close(clone.call()); assertTrue(true); Git git = Git.open(jgit2Folder); File file = new File(jgit2Folder, "NONBARE"); OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET); BufferedWriter w = new BufferedWriter(os); w.write("// " + new Date().toString() + "\n"); w.close(); git.add().addFilepattern(file.getName()).call(); git.commit().setMessage("test commit followed by push to non-bare repository").call(); try { git.push().setPushAll().call(); assertTrue(false); } catch (Exception e) { assertTrue(e.getCause().getMessage().contains("git-receive-pack not permitted")); } close(git); }
public void renameRole(String roleName, String newRoleName, User currentUser) throws IOException { Assert.hasLength(roleName); 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 { Util.closeQuietly(repo); } }
protected RevCommit doRename( Git git, File rootDir, String branch, String oldPath, String newPath, String commitMessage, PersonIdent personIdent) throws Exception { File file = getFile(rootDir, oldPath); File newFile = getFile(rootDir, newPath); if (file.exists()) { File parentFile = newFile.getParentFile(); parentFile.mkdirs(); if (!parentFile.exists()) { throw new IOException( "Could not create directory " + parentFile + " when trying to move " + file + " to " + newFile + ". Maybe a file permission issue?"); } file.renameTo(newFile); String filePattern = getFilePattern(newPath); git.add().addFilepattern(filePattern).call(); CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(commitMessage); return commitThenPush(git, branch, commit); } else { return null; } }
@Test public void finishHotfixMasterIsTagged() throws Exception { Git git = RepoUtil.createRepositoryWithMasterAndTag(newDir()); JGitFlowInitCommand initCommand = new JGitFlowInitCommand(); JGitFlow flow = initCommand.setDirectory(git.getRepository().getWorkTree()).call(); flow.hotfixStart("1.1").call(); // Make sure we move away from master on a hotfix branch // This is important to validate JGITFFLOW-14 // create a new commit File junkFile = new File(git.getRepository().getWorkTree(), "junk.txt"); FileUtils.writeStringToFile(junkFile, "I am junk"); git.add().addFilepattern(junkFile.getName()).call(); git.commit().setMessage("committing junk file").call(); flow.hotfixFinish("1.1").setNoTag(false).call(); // we should be on develop branch assertEquals(flow.getDevelopBranchName(), git.getRepository().getBranch()); // There should be a tag reference Ref hotfixTagRef = git.getRepository().getTags().get(flow.getVersionTagPrefix() + "1.1"); assertNotNull(hotfixTagRef); RevTag hotfixTag = new RevWalk(git.getRepository()).parseTag(hotfixTagRef.getObjectId()); assertNotNull(hotfixTag); // Check that latest tag has moved assertFalse(getTaggedCommit(git, "1.1").equals(getTaggedCommit(git, "1.0"))); }
/** * Saves a user. * * @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 { Util.closeQuietly(repo); } }
@Test(expected = BranchOutOfDateException.class) public void finishHotfixMasterBehindRemoteWithFetch() throws Exception { Git git = null; Git remoteGit = null; remoteGit = RepoUtil.createRepositoryWithMasterAndTag(newDir()); git = Git.cloneRepository() .setDirectory(newDir()) .setURI("file://" + remoteGit.getRepository().getWorkTree().getPath()) .call(); JGitFlowInitCommand initCommand = new JGitFlowInitCommand(); JGitFlow flow = initCommand.setDirectory(git.getRepository().getWorkTree()).call(); flow.hotfixStart("1.1").call(); // do a commit to the remote develop branch remoteGit.checkout().setName(flow.getDevelopBranchName()); File junkFile = new File(remoteGit.getRepository().getWorkTree(), "junk.txt"); FileUtils.writeStringToFile(junkFile, "I am junk"); remoteGit.add().addFilepattern(junkFile.getName()).call(); remoteGit.commit().setMessage("adding junk file").call(); flow.hotfixFinish("1.1").setFetch(true).call(); }
@Test public void testAutoCRLFInput() throws Exception { try (Git git = new Git(db)) { FileBasedConfig config = db.getConfig(); // Make sure core.autocrlf is false before adding config.setEnum( ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, AutoCRLF.FALSE); config.save(); // File is already in repository with CRLF writeTrashFile("crlf.txt", "this\r\ncontains\r\ncrlf\r\n"); git.add().addFilepattern("crlf.txt").call(); git.commit().setMessage("Add crlf.txt").call(); // Now set core.autocrlf to input config.setEnum( ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, AutoCRLF.INPUT); config.save(); FileTreeIterator iterator = new FileTreeIterator(db); IndexDiff diff = new IndexDiff(db, Constants.HEAD, iterator); diff.diff(); assertTrue( "Expected no modified files, but there were: " + diff.getModified(), diff.getModified().isEmpty()); } }
/** * Saves a role. * * @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 { Util.closeQuietly(repo); } }
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); } 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(); } }
private void doCommitPush(Git git, String message) throws GitAPIException { git.commit() .setAuthor(getAuthorName(), "*****@*****.**") .setCommitter("opal", "*****@*****.**") .setMessage(message) .call(); git.push().setPushAll().setRemote("origin").call(); }
@Test public void testStageState_simulated_bug() throws Exception { try (Git git = new Git(db)) { writeTrashFile("a", "content"); git.add().addFilepattern("a").call(); RevCommit initialCommit = git.commit().setMessage("initial commit").call(); // create branch and add a new file final String branchName = Constants.R_HEADS + "branch"; createBranch(initialCommit, branchName); checkoutBranch(branchName); writeTrashFile("b", "second file content - branch"); git.add().addFilepattern("b").call(); git.commit().setMessage("branch commit").call(); // checkout master and add the same new file checkoutBranch(Constants.R_HEADS + Constants.MASTER); writeTrashFile("b", "second file content - master"); git.add().addFilepattern("b").call(); git.commit().setMessage("master commit").call(); // Simulate a failed merge of branch into master DirCacheBuilder builder = db.lockDirCache().builder(); DirCacheEntry entry = createEntry("a", FileMode.REGULAR_FILE, 0, "content"); builder.add(entry); entry = createEntry("b", FileMode.REGULAR_FILE, 2, "second file content - master"); builder.add(entry); entry = createEntry("b", FileMode.REGULAR_FILE, 3, "second file content - branch"); builder.add(entry); builder.commit(); FileTreeIterator iterator = new FileTreeIterator(db); IndexDiff diff = new IndexDiff(db, Constants.HEAD, iterator); diff.diff(); assertTrue(diff.getChanged().isEmpty()); assertTrue(diff.getAdded().isEmpty()); assertTrue(diff.getRemoved().isEmpty()); assertTrue(diff.getMissing().isEmpty()); assertTrue(diff.getModified().isEmpty()); assertEquals(1, diff.getConflicting().size()); assertTrue(diff.getConflicting().contains("b")); assertEquals(StageState.BOTH_ADDED, diff.getConflictingStageStates().get("b")); assertTrue(diff.getUntrackedFolders().isEmpty()); } }
public static void commit(File directory, String message) throws GitException { try { Git git = openRepository(directory); git.commit().setMessage(message).call(); } catch (GitAPIException e) { throw new GitException("Commit " + message + " in " + directory + " failed", e); } }
private void commit(Git git, String message) throws GitAPIException { Status status = git.status().call(); if (!status.getAdded().isEmpty() || !status.getChanged().isEmpty() || !status.getRemoved().isEmpty()) { git.commit().setMessage(message).call(); } }
@Test public void resolveUpstream() throws Exception { Git git = new Git(db); writeTrashFile("file.txt", "content"); git.add().addFilepattern("file.txt").call(); RevCommit c1 = git.commit().setMessage("create file").call(); writeTrashFile("file2.txt", "content"); RefUpdate updateRemoteRef = db.updateRef("refs/remotes/origin/main"); updateRemoteRef.setNewObjectId(c1); updateRemoteRef.update(); db.getConfig().setString("branch", "master", "remote", "origin"); db.getConfig().setString("branch", "master", "merge", "refs/heads/main"); db.getConfig().setString("remote", "origin", "url", "git://example.com/here"); db.getConfig().setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); git.add().addFilepattern("file2.txt").call(); git.commit().setMessage("create file").call(); assertEquals("refs/remotes/origin/main", db.simplify("@{upstream}")); }
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { switch (requestCode) { case GitActivity.REQUEST_CLONE: // if we get here with a RESULT_OK then it's probably OK :) settings.edit().putBoolean("repository_initialized", true).apply(); break; case PgpHandler.REQUEST_CODE_ENCRYPT: Git git = new Git(PasswordRepository.getRepository(new File(""))); GitAsyncTask tasks = new GitAsyncTask(this, false, false, CommitCommand.class); tasks.execute( git.add().addFilepattern("."), git.commit() .setMessage( this.getResources().getString(R.string.add_commit_text) + data.getExtras().getString("NAME") + this.getResources().getString(R.string.from_store))); refreshListAdapter(); break; case GitActivity.REQUEST_INIT: initializeRepositoryInfo(); break; case GitActivity.REQUEST_PULL: updateListAdapter(); break; case HOME: checkLocalRepository(); break; case NEW_REPO_BUTTON: initializeRepositoryInfo(); break; case CLONE_REPO_BUTTON: // duplicate code if (settings.getBoolean("git_external", false) && settings.getString("git_external_repo", null) != null) { String externalRepoPath = settings.getString("git_external_repo", null); File dir = externalRepoPath != null ? new File(externalRepoPath) : null; if (dir != null && dir.exists() && dir.isDirectory() && !FileUtils.listFiles(dir, null, true).isEmpty() && !PasswordRepository.getPasswords( dir, PasswordRepository.getRepositoryDirectory(this)) .isEmpty()) { PasswordRepository.closeRepository(); checkLocalRepository(); return; // if not empty, just show me the passwords! } } Intent intent = new Intent(activity, GitActivity.class); intent.putExtra("Operation", GitActivity.REQUEST_CLONE); startActivityForResult(intent, GitActivity.REQUEST_CLONE); break; } } }
@Test public void finishHotfixWithNewCommitAndReleaseBranch() throws Exception { Git git = RepoUtil.createRepositoryWithMasterAndTag(newDir()); JGitFlowInitCommand initCommand = new JGitFlowInitCommand(); JGitFlow flow = initCommand.setDirectory(git.getRepository().getWorkTree()).call(); flow.releaseStart("1.1").call(); String releaseName = "release/1.1"; flow.git().checkout().setName("master").call(); flow.hotfixStart("1.1.1").call(); // create a new commit File junkFile = new File(git.getRepository().getWorkTree(), "junk.txt"); FileUtils.writeStringToFile(junkFile, "I am junk"); git.add().addFilepattern(junkFile.getName()).call(); RevCommit commit = git.commit().setMessage("committing junk file").call(); // make sure develop doesn't report our commit yet assertFalse(GitHelper.isMergedInto(git, commit, flow.getDevelopBranchName())); // make sure release doesn't report our commit yet assertFalse(GitHelper.isMergedInto(git, commit, releaseName)); // try to finish flow.hotfixFinish("1.1.1").setKeepBranch(false).call(); // we should be on develop branch assertEquals(flow.getDevelopBranchName(), git.getRepository().getBranch()); // hotfix branch should be gone Ref ref2check = git.getRepository().getRef(flow.getHotfixBranchPrefix() + "1.1.1"); assertNull(ref2check); // the develop branch should have our commit assertTrue(GitHelper.isMergedInto(git, commit, flow.getDevelopBranchName())); // since fast-forward is suppressed the latest commit on develop should be a merge commit with 2 // parents assertEquals(2, GitHelper.getLatestCommit(git, flow.getDevelopBranchName()).getParentCount()); // the master branch should have our commit assertTrue(GitHelper.isMergedInto(git, commit, getTaggedCommit(git, "1.1.1"))); // since fast-forward is suppressed the latest commit on master should be a merge commit with 2 // parents assertEquals(2, GitHelper.getLatestCommit(git, getTaggedCommit(git, "1.1.1")).getParentCount()); // the release branch should have our commit assertTrue(GitHelper.isMergedInto(git, commit, releaseName)); // since fast-forward is suppressed the latest commit on the release branch should be a merge // commit with 2 parents assertEquals(2, GitHelper.getLatestCommit(git, releaseName).getParentCount()); }
@Test public void resolveExprSimple() throws Exception { Git git = new Git(db); writeTrashFile("file.txt", "content"); git.add().addFilepattern("file.txt").call(); git.commit().setMessage("create file").call(); assertEquals("master", db.simplify("master")); assertEquals("refs/heads/master", db.simplify("refs/heads/master")); assertEquals("HEAD", db.simplify("HEAD")); }
/** * Commits the current index * * @param message commit message * @return commit object * @throws NoHeadException * @throws NoMessageException * @throws UnmergedPathException * @throws ConcurrentRefUpdateException * @throws JGitInternalException * @throws WrongRepositoryStateException */ public RevCommit commit(String message) throws NoHeadException, NoMessageException, UnmergedPathException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException { Git git = new Git(repository); CommitCommand commitCommand = git.commit(); commitCommand.setAuthor("J. Git", "*****@*****.**"); commitCommand.setCommitter(commitCommand.getAuthor()); commitCommand.setMessage(message); return commitCommand.call(); }
/** @throws Exception */ @Test public void testUntrackedFolders() throws Exception { try (Git git = new Git(db)) { IndexDiff diff = new IndexDiff(db, Constants.HEAD, new FileTreeIterator(db)); diff.diff(); assertEquals(Collections.EMPTY_SET, diff.getUntrackedFolders()); writeTrashFile("readme", ""); writeTrashFile("src/com/A.java", ""); writeTrashFile("src/com/B.java", ""); writeTrashFile("src/org/A.java", ""); writeTrashFile("src/org/B.java", ""); writeTrashFile("target/com/A.java", ""); writeTrashFile("target/com/B.java", ""); writeTrashFile("target/org/A.java", ""); writeTrashFile("target/org/B.java", ""); git.add().addFilepattern("src").addFilepattern("readme").call(); git.commit().setMessage("initial").call(); diff = new IndexDiff(db, Constants.HEAD, new FileTreeIterator(db)); diff.diff(); assertEquals(new HashSet<String>(Arrays.asList("target")), diff.getUntrackedFolders()); writeTrashFile("src/tst/A.java", ""); writeTrashFile("src/tst/B.java", ""); diff = new IndexDiff(db, Constants.HEAD, new FileTreeIterator(db)); diff.diff(); assertEquals( new HashSet<String>(Arrays.asList("target", "src/tst")), diff.getUntrackedFolders()); git.rm().addFilepattern("src/com/B.java").addFilepattern("src/org").call(); git.commit().setMessage("second").call(); writeTrashFile("src/org/C.java", ""); diff = new IndexDiff(db, Constants.HEAD, new FileTreeIterator(db)); diff.diff(); assertEquals( new HashSet<String>(Arrays.asList("src/org", "src/tst", "target")), diff.getUntrackedFolders()); } }
@Test public void finishHotfixWithMultipleCommits() throws Exception { Git git = RepoUtil.createRepositoryWithMasterAndTag(newDir()); JGitFlowInitCommand initCommand = new JGitFlowInitCommand(); JGitFlow flow = initCommand.setDirectory(git.getRepository().getWorkTree()).call(); flow.hotfixStart("1.1").call(); // create a new commit File junkFile = new File(git.getRepository().getWorkTree(), "junk.txt"); FileUtils.writeStringToFile(junkFile, "I am junk"); git.add().addFilepattern(junkFile.getName()).call(); RevCommit commit = git.commit().setMessage("committing junk file").call(); // create second commit File junkFile2 = new File(git.getRepository().getWorkTree(), "junk2.txt"); FileUtils.writeStringToFile(junkFile2, "I am junk, and so are you"); git.add().addFilepattern(junkFile2.getName()).call(); RevCommit commit2 = git.commit().setMessage("updating junk file").call(); // make sure develop doesn't have our commits yet assertFalse(GitHelper.isMergedInto(git, commit, flow.getDevelopBranchName())); assertFalse(GitHelper.isMergedInto(git, commit2, flow.getDevelopBranchName())); // try to finish flow.hotfixFinish("1.1").call(); // we should be on develop branch assertEquals(flow.getDevelopBranchName(), git.getRepository().getBranch()); // release branch should be gone Ref ref2check = git.getRepository().getRef(flow.getHotfixBranchPrefix() + "1.1"); assertNull(ref2check); // the develop branch should have both of our commits now assertTrue(GitHelper.isMergedInto(git, commit, flow.getDevelopBranchName())); assertTrue(GitHelper.isMergedInto(git, commit2, flow.getDevelopBranchName())); // the master branch should have both of our commits now assertTrue(GitHelper.isMergedInto(git, commit, getTaggedCommit(git, "1.1"))); assertTrue(GitHelper.isMergedInto(git, commit2, getTaggedCommit(git, "1.1"))); }
/** * Adds changes to the staging index. Then makes commit. * * @param message the commit message * @param name the name of the committer used for the commit * @param email the email of the committer used for the commit * @param all if set to true, command will automatically stages files that have been modified and * deleted, but new files not known by the repository are not affected. This corresponds to * the parameter -a on the command line. * @throws NoHeadException * @throws NoMessageException * @throws UnmergedPathsException * @throws ConcurrentRefUpdateException * @throws WrongRepositoryStateException * @throws GitAPIException * @throws IOException */ public void commit(String message, String name, String email, boolean all) throws NoHeadException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException, WrongRepositoryStateException, GitAPIException, IOException { CommitCommand commitCommand = git.commit(); commitCommand.setMessage(message); commitCommand.setCommitter(name, email); commitCommand.setAuthor(name, email); commitCommand.setAll(all); commitCommand.call(); }
@Test public void testConflicting() throws Exception { try (Git git = new Git(db)) { writeTrashFile("a", "1\na\n3\n"); writeTrashFile("b", "1\nb\n3\n"); git.add().addFilepattern("a").addFilepattern("b").call(); RevCommit initialCommit = git.commit().setMessage("initial").call(); // create side branch with two modifications createBranch(initialCommit, "refs/heads/side"); checkoutBranch("refs/heads/side"); writeTrashFile("a", "1\na(side)\n3\n"); writeTrashFile("b", "1\nb\n3\n(side)"); git.add().addFilepattern("a").addFilepattern("b").call(); RevCommit secondCommit = git.commit().setMessage("side").call(); // update a on master to generate conflict checkoutBranch("refs/heads/master"); writeTrashFile("a", "1\na(main)\n3\n"); git.add().addFilepattern("a").call(); git.commit().setMessage("main").call(); // merge side with master MergeResult result = git.merge().include(secondCommit.getId()).setStrategy(MergeStrategy.RESOLVE).call(); assertEquals(MergeStatus.CONFLICTING, result.getMergeStatus()); } FileTreeIterator iterator = new FileTreeIterator(db); IndexDiff diff = new IndexDiff(db, Constants.HEAD, iterator); diff.diff(); assertEquals("[b]", new TreeSet<String>(diff.getChanged()).toString()); assertEquals("[]", diff.getAdded().toString()); assertEquals("[]", diff.getRemoved().toString()); assertEquals("[]", diff.getMissing().toString()); assertEquals("[]", diff.getModified().toString()); assertEquals("[a]", diff.getConflicting().toString()); assertEquals(StageState.BOTH_MODIFIED, diff.getConflictingStageStates().get("a")); assertEquals(Collections.EMPTY_SET, diff.getUntrackedFolders()); }
private void commit(Git git, String message) throws IOException { CommitCommand commit = git.commit(); try { commit.setMessage(message).call(); } catch (GitAPIException e) { throw new IOException(e); } catch (UnmergedPathException e) { throw new IOException(e); } catch (JGitInternalException e) { throw new IOException(e); } }
@Test public void testGitPgm() throws Exception { Path targetParent = detectTargetFolder().getParent(); Path serverDir = getTempTargetRelativeFile(getClass().getSimpleName()); // // TODO: the GitpgmCommandFactory is kept in the test tree // TODO: because it's quite limited for now // try (SshServer sshd = setupTestServer()) { sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory())); sshd.setCommandFactory( new GitPgmCommandFactory(Utils.resolveRelativeRemotePath(targetParent, serverDir))); sshd.start(); int port = sshd.getPort(); try { Utils.deleteRecursive(serverDir); try (SshClient client = setupTestClient()) { client.start(); try (ClientSession session = client .connect(getCurrentTestName(), SshdSocketAddress.LOCALHOST_IP, port) .verify(7L, TimeUnit.SECONDS) .getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); Path repo = serverDir.resolve(getCurrentTestName()); Git.init().setDirectory(repo.toFile()).call(); Git git = Git.open(repo.toFile()); git.commit() .setMessage("First Commit") .setCommitter(getCurrentTestName(), "*****@*****.**") .call(); Path readmeFile = Files.createFile(repo.resolve("readme.txt")); String commandPrefix = "git --git-dir " + repo.getFileName(); execute(session, commandPrefix + " add " + readmeFile.getFileName()); execute(session, commandPrefix + " commit -m \"readme\""); } finally { client.stop(); } } } finally { sshd.stop(); } } }