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(); }
public static List<File> getNotIgnoredFilesOfRepo(File directory) throws GitException { Git git = openRepository(directory); Repository repo = null; repo = git.getRepository(); List<File> foundFiles = new ArrayList<>(); TreeWalk treeWalk = null; try { treeWalk = new TreeWalk(repo); FileTreeIterator tree = new FileTreeIterator(repo); treeWalk.addTree(tree); treeWalk.setRecursive(false); while (treeWalk.next()) { WorkingTreeIterator iterator = treeWalk.getTree(0, WorkingTreeIterator.class); if (!iterator.isEntryIgnored()) if (treeWalk.isSubtree()) { treeWalk.enterSubtree(); } else { File file = new File(directory, treeWalk.getPathString()); foundFiles.add(file); } } } catch (IOException e) { throw new GitException("Listing of non-ignored files in " + directory + " failed", e); } finally { if (treeWalk != null) treeWalk.close(); } return foundFiles; }
private void completeUndo(Git git) { try { if (isUndo(git)) { git.checkout().setName("master").call(); git.merge() .setStrategy(MergeStrategy.THEIRS) .include(git.getRepository().resolve("undo")) .setCommit(true) .call(); git.branchDelete().setBranchNames("undo").call(); } } catch (RuntimeException ex) { } catch (CheckoutConflictException e) { throw new RuntimeException(e); } catch (RefAlreadyExistsException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidRefNameException e) { throw new RuntimeException(e); } catch (RefNotFoundException e) { throw new RuntimeException(e); } catch (GitAPIException e) { throw new RuntimeException(e); } }
@Test public void dontPackHEAD_nonBare() throws Exception { BranchBuilder bb = tr.branch("refs/heads/side"); RevCommit first = bb.commit().add("A", "A").add("B", "B").create(); bb.commit().add("A", "A2").add("B", "B2").create(); Git git = Git.wrap(repo); // check for the unborn branch master. HEAD should point to master and // master doesn't exist. assertEquals(repo.exactRef("HEAD").getTarget().getName(), "refs/heads/master"); assertNull(repo.exactRef("HEAD").getTarget().getObjectId()); gc.packRefs(); assertSame(repo.exactRef("HEAD").getStorage(), Storage.LOOSE); assertEquals(repo.exactRef("HEAD").getTarget().getName(), "refs/heads/master"); assertNull(repo.exactRef("HEAD").getTarget().getObjectId()); git.checkout().setName("refs/heads/side").call(); gc.packRefs(); assertSame(repo.exactRef("HEAD").getStorage(), Storage.LOOSE); // check for detached HEAD git.checkout().setName(first.getName()).call(); gc.packRefs(); assertSame(repo.exactRef("HEAD").getStorage(), Storage.LOOSE); }
public static void updateRepository(String localPath, String remotePath) throws Exception { Repository localRepo; try { localRepo = new FileRepository(localPath + "/.git"); Git git = new Git(localRepo); { AsposeConstants.println("Cloning Repository [" + remotePath + "]...."); } // First try to clone the repository try { Git.cloneRepository().setURI(remotePath).setDirectory(new File(localPath)).call(); } catch (Exception ex) { // If clone fails, try to pull the changes try { git.pull().call(); } catch (Exception exPull) { // Pull also failed. Throw this exception to caller { AsposeConstants.println("Pull also failed."); } throw exPull; // throw it } } } catch (Exception ex) { throw new Exception("Could not download Repository from Github. Error: " + ex.getMessage()); } }
private IStatus doClone() { try { File cloneFolder = new File(clone.getContentLocation().getPath()); if (!cloneFolder.exists()) { cloneFolder.mkdir(); } CloneCommand cc = Git.cloneRepository(); cc.setBare(false); cc.setCredentialsProvider(credentials); cc.setDirectory(cloneFolder); cc.setRemote(Constants.DEFAULT_REMOTE_NAME); cc.setURI(clone.getUrl()); Git git = cc.call(); // Configure the clone, see Bug 337820 setMessage(NLS.bind("Configuring {0}...", clone.getUrl())); GitCloneHandlerV1.doConfigureClone(git, user); git.getRepository().close(); } catch (IOException e) { return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e); } catch (CoreException e) { return e.getStatus(); } catch (GitAPIException e) { return getGitAPIExceptionStatus(e, "Error cloning git repository"); } catch (JGitInternalException e) { return getJGitInternalExceptionStatus(e, "Error cloning git repository"); } catch (Exception e) { return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e); } return Status.OK_STATUS; }
/** * This will create or refresh the working copy. If the working copy cannot be pulled cleanly this * method will fail. * * @param gitRepositoryUri remote git repository URI string * @return git * @throws GitAPIException * @throws IOException * @throws URISyntaxException */ private Git getGit(final String gitRepositoryUri) throws GitAPIException, IOException, URISyntaxException { final Git cachedGit = gitCache.get(gitRepositoryUri); if (cachedGit != null) { return cachedGit; } final File gitDir = File.createTempFile( gitRepositoryUri.replaceAll("[^A-Za-z]", "_"), "wagon-git"); // $NON-NLS-1$ gitDir.delete(); gitDir.mkdir(); credentialsProvider = new UsernamePasswordCredentialsProvider( getAuthenticationInfo().getUserName(), getAuthenticationInfo().getPassword() == null ? "" //$NON-NLS-1$ : getAuthenticationInfo().getPassword()); final Git git = Git.cloneRepository() .setURI(gitRepositoryUri) .setCredentialsProvider(credentialsProvider) .setBranch(gitUri.getBranchName()) .setDirectory(gitDir) .call(); if (!gitUri.getBranchName().equals(git.getRepository().getBranch())) { LOG.log(Level.INFO, "missingbranch", gitUri.getBranchName()); final RefUpdate refUpdate = git.getRepository().getRefDatabase().newUpdate(Constants.HEAD, true); refUpdate.setForceUpdate(true); refUpdate.link("refs/heads/" + gitUri.getBranchName()); // $NON-NLS-1$ } gitCache.put(gitRepositoryUri, git); return git; }
public static void stashApply(final Git repo, String... stashRef) throws GitAPIException { if (stashRef.length >= 1 && !Strings.isNullOrEmpty(stashRef[0])) { repo.stashApply().setStashRef(stashRef[0]).call(); } else { repo.stashApply().call(); } }
private void doWriteGitViews( @Nonnull String datasourceName, @Nonnull Iterable<View> views, @Nullable String comment) { File localRepo = null; try { // Fetch or clone a tmp working directory localRepo = cloneDatasourceViewsGit(datasourceName); // Serialize all view files in the repo List<String> varFilesToRemove = Lists.newArrayList(); StringBuilder message = new StringBuilder(); for (View view : views) { doWriteGitView(localRepo, view, varFilesToRemove); if (message.length() > 0) { message.append(", "); } message.append(view.getName()); } // Push changes Git git = new Git(new FileRepository(new File(localRepo, ".git"))); for (String toRemove : varFilesToRemove) { git.rm().addFilepattern(toRemove).call(); } git.add().addFilepattern(".").call(); doCommitPush(git, Strings.isNullOrEmpty(comment) ? "Update " + message : comment); } catch (Exception e) { throw new RuntimeException( "Failed writing views in git for datasource: " + datasourceName, e); } finally { if (localRepo != null) localRepo.delete(); } }
private Iterable<RevCommit> getCommitsFromTag(String treeName) { try { List<Ref> call = git.tagList().call(); Iterable<RevCommit> logs = null; for (Ref ref : call) { if (ref.getName().equals(treeName)) { LogCommand log = git.log(); Ref peeledRef = repository.peel(ref); if (peeledRef.getPeeledObjectId() != null) { log.add(peeledRef.getPeeledObjectId()); } else { log.add(ref.getObjectId()); } logs = log.call(); return logs; } } return null; } catch (GitAPIException e) { throw new VisMinerAPIException(e.getMessage(), e); } catch (MissingObjectException e) { throw new VisMinerAPIException(e.getMessage(), e); } catch (IncorrectObjectTypeException e) { throw new VisMinerAPIException(e.getMessage(), e); } }
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 testGetCloneAndPull() throws Exception { // see bug 339254 URI workspaceLocation = createWorkspace(getMethodName()); String workspaceId = getWorkspaceId(workspaceLocation); JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null); IPath clonePath = new Path("file").append(project.getString(ProtocolConstants.KEY_ID)).makeAbsolute(); String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION); // get clones for workspace WebRequest request = listGitClonesRequest(workspaceId, null); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject clones = new JSONObject(response.getText()); JSONArray clonesArray = clones.getJSONArray(ProtocolConstants.KEY_CHILDREN); assertEquals(1, clonesArray.length()); Git git = new Git(getRepositoryForContentLocation(contentLocation)); // TODO: replace with RESTful API when ready, see bug 339114 PullResult pullResult = git.pull().call(); assertEquals(pullResult.getMergeResult().getMergeStatus(), MergeStatus.ALREADY_UP_TO_DATE); assertEquals(RepositoryState.SAFE, git.getRepository().getRepositoryState()); }
/** * 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); } }
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(); } }
/** Performs the given operations on a clean git repository */ protected <T> T gitOperation(PersonIdent personIdent, Callable<T> callable) { synchronized (lock) { try { // lets check if we have done a commit yet... boolean hasHead = true; try { git.log().all().call(); } catch (NoHeadException e) { hasHead = false; } // TODO pull if we have a remote repo if (hasHead) { // lets stash any local changes just in case.. git.stashCreate() .setPerson(personIdent) .setWorkingDirectoryMessage("Stash before a write") .setRef("HEAD") .call(); } return callable.call(); } catch (Exception e) { throw new RuntimeIOException(e); } } }
@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 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()); } }
/* * Use the binary git repo and/or the remote service to figure out * the new commits made since the last pull on source repository. */ public void findNewCommits() throws GitException { // get the history from binary repository Git bingit = Git.wrap(binaryRepository); RevWalk binwalk = new RevWalk(binaryRepository); Iterable<RevCommit> logs; try { logs = bingit.log().call(); Iterator<RevCommit> i = logs.iterator(); while (i.hasNext()) { RevCommit commit = binwalk.parseCommit(i.next()); System.out.println(commit.getFullMessage()); } } catch (NoHeadException e) { // TODO Auto-generated catch block throw new GitException(e); } catch (GitAPIException e) { throw new GitException(e); } catch (MissingObjectException e) { throw new GitException(e); } catch (IncorrectObjectTypeException e) { throw new GitException(e); } catch (IOException e) { throw new GitException(e); } }
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); } }
@Test public void dontPackHEAD_bare() throws Exception { BranchBuilder bb = tr.branch("refs/heads/side"); bb.commit().add("A", "A").add("B", "B").create(); RevCommit second = bb.commit().add("A", "A2").add("B", "B2").create(); // Convert the repo to be bare FileBasedConfig cfg = repo.getConfig(); cfg.setBoolean( ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_BARE, true); cfg.save(); Git git = Git.open(repo.getDirectory()); repo = (FileRepository) git.getRepository(); // check for the unborn branch master. HEAD should point to master and // master doesn't exist. assertEquals(repo.exactRef("HEAD").getTarget().getName(), "refs/heads/master"); assertNull(repo.exactRef("HEAD").getTarget().getObjectId()); gc.packRefs(); assertSame(repo.exactRef("HEAD").getStorage(), Storage.LOOSE); assertEquals(repo.exactRef("HEAD").getTarget().getName(), "refs/heads/master"); assertNull(repo.exactRef("HEAD").getTarget().getObjectId()); // check for non-detached HEAD repo.updateRef(Constants.HEAD).link("refs/heads/side"); gc.packRefs(); assertSame(repo.exactRef("HEAD").getStorage(), Storage.LOOSE); assertEquals(repo.exactRef("HEAD").getTarget().getObjectId(), second.getId()); }
/** * 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); } }
@Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { try { String localPath = args[0].getStringValue(); if (!(localPath.endsWith("/"))) localPath += File.separator; // Repository localRepo = new FileRepository(localPath + ".git"); // Git git = new Git(localRepo); Git git = Git.open(new Resource(localPath), FS); MemTreeBuilder builder = context.getDocumentBuilder(); AttributesImpl attribs = new AttributesImpl(); attribs.addAttribute(NAMESPACE_URI, "local-path", PREFIX + ":local-path", "CDATA", localPath); int nodeNr = builder.startElement(LOG_ELEMENT, attribs); for (RevCommit commit : git.log().call()) { // commit.getParentCount(); // commit.getParents(); attribs = new AttributesImpl(); attribs.addAttribute(NAMESPACE_URI, "id", PREFIX + ":id", "CDATA", commit.name()); attribs.addAttribute( NAMESPACE_URI, "time", PREFIX + ":time", "CDATA", String.valueOf(commit.getCommitTime())); builder.startElement(COMMIT_ELEMENT, attribs); PersonIdent authorIdent = commit.getAuthorIdent(); builder.startElement(AUTHOR_ELEMENT, null); builder.startElement(AUTHOR_NAME_ELEMENT, null); builder.characters(authorIdent.getName()); builder.endElement(); builder.startElement(AUTHOR_EMAIL_ELEMENT, null); builder.characters(authorIdent.getEmailAddress()); builder.endElement(); builder.endElement(); builder.startElement(MESSAGE_ELEMENT, null); builder.characters(commit.getFullMessage()); builder.endElement(); builder.endElement(); } builder.endElement(); return builder.getDocument().getNode(nodeNr); } catch (Throwable e) { throw new XPathException(this, Module.EXGIT001, e); } }
@Override protected IStatus performJob() { try { // list all tags File gitDir = GitUtils.getGitDir(path); Repository db = new FileRepository(gitDir); Git git = new Git(db); List<Ref> refs = git.tagList().call(); JSONObject result = new JSONObject(); List<Tag> tags = new ArrayList<Tag>(); for (Ref ref : refs) { Tag tag = new Tag(cloneLocation, db, ref); tags.add(tag); } Collections.sort(tags, Tag.COMPARATOR); JSONArray children = new JSONArray(); int firstTag = pageSize > 0 ? pageSize * (pageNo - 1) : 0; int lastTag = pageSize > 0 ? firstTag + pageSize - 1 : tags.size() - 1; lastTag = lastTag > tags.size() - 1 ? tags.size() - 1 : lastTag; if (pageNo > 1 && baseLocation != null) { String prev = baseLocation + "?page=" + (pageNo - 1) + "&pageSize=" + pageSize; if (commitsSize > 0) { prev += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize; } result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, prev); } if (lastTag < tags.size() - 1) { String next = baseLocation + "?page=" + (pageNo + 1) + "&pageSize=" + pageSize; if (commitsSize > 0) { next += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize; } result.put(ProtocolConstants.KEY_NEXT_LOCATION, next); } for (int i = firstTag; i <= lastTag; i++) { Tag tag = tags.get(i); if (this.commitsSize == 0) { children.put(tag.toJSON()); } else { // add info about commits if requested LogCommand lc = git.log(); String toCommitName = tag.getRevCommitName(); ObjectId toCommitId = db.resolve(toCommitName); Ref toCommitRef = db.getRef(toCommitName); toCommitId = getCommitObjectId(db, toCommitId); lc.add(toCommitId); lc.setMaxCount(this.commitsSize); Iterable<RevCommit> commits = lc.call(); Log log = new Log(cloneLocation, db, commits, null, null, toCommitRef); children.put(tag.toJSON(log.toJSON(1, commitsSize))); } } result.put(ProtocolConstants.KEY_CHILDREN, children); result.put(ProtocolConstants.KEY_TYPE, Tag.TYPE); return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result); } catch (Exception e) { String msg = NLS.bind("An error occured when listing tags for {0}", path); return new Status(IStatus.ERROR, GitActivator.PI_GIT, msg, e); } }
@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 testUnauthorizedLoginClone() throws Exception { // restrict repository access RepositoryModel model = GitBlit.self().getRepositoryModel("ticgit.git"); model.accessRestriction = AccessRestrictionType.CLONE; model.authorizationControl = AuthorizationControl.NAMED; UserModel user = new UserModel("james"); user.password = "******"; GitBlit.self().updateUserModel(user.username, user, true); GitBlit.self().updateRepositoryModel(model.name, model, false); FileUtils.delete(ticgit2Folder, FileUtils.RECURSIVE); // delete any existing working folder boolean cloned = false; try { CloneCommand clone = Git.cloneRepository(); clone.setURI(MessageFormat.format("{0}/git/ticgit.git", url)); clone.setDirectory(ticgit2Folder); clone.setBare(false); clone.setCloneAllBranches(true); clone.setCredentialsProvider( new UsernamePasswordCredentialsProvider(user.username, user.password)); close(clone.call()); cloned = true; } catch (Exception e) { // swallow the exception which we expect } assertFalse("Unauthorized login cloned a repository?!", cloned); FileUtils.delete(ticgit2Folder, FileUtils.RECURSIVE); // switch to authenticated model.authorizationControl = AuthorizationControl.AUTHENTICATED; GitBlit.self().updateRepositoryModel(model.name, model, false); // try clone again cloned = false; CloneCommand clone = Git.cloneRepository(); clone.setURI(MessageFormat.format("{0}/git/ticgit.git", url)); clone.setDirectory(ticgit2Folder); clone.setBare(false); clone.setCloneAllBranches(true); clone.setCredentialsProvider( new UsernamePasswordCredentialsProvider(user.username, user.password)); close(clone.call()); cloned = true; assertTrue("Authenticated login could not clone!", cloned); FileUtils.delete(ticgit2Folder, FileUtils.RECURSIVE); // restore anonymous repository access model.accessRestriction = AccessRestrictionType.NONE; model.authorizationControl = AuthorizationControl.NAMED; GitBlit.self().updateRepositoryModel(model.name, model, false); GitBlit.self().deleteUser(user.username); }
<T> T execute(GitOperation<T> gitOperation) { Git git = openRepository(); try { return guarded(() -> gitOperation.execute(git)); } finally { git.close(); } }
private void doCommitPush(Git git, String message) throws GitAPIException { git.commit() .setAuthor(getAuthorName(), "*****@*****.**") .setCommitter("opal", "*****@*****.**") .setMessage(message) .call(); git.push().setPushAll().setRemote("origin").call(); }
public static void checkout(File directory, String hash) throws GitException { Git git = openRepository(directory); try { git.checkout().setName(hash).call(); } catch (GitAPIException e) { throw new GitException("Checkout in directory " + directory + " failed", e); } }
/** * This will get the file object for the given resource relative to the {@link Git} specified for * the connection. It will handle resources where it jumps up past the parent folder. * * @param resourceName resource name. * @return file used for the resourse. * @throws IOException * @throws GitAPIException * @throws URISyntaxException */ private File getFileForResource(final String resourceName) throws GitAPIException, IOException, URISyntaxException { // /foo/bar/foo.git + ../bar.git == /foo/bar/bar.git + / // /foo/bar/foo.git + ../bar.git/abc == /foo/bar/bar.git + /abc final GitUri resolved = gitUri.resolve(resourceName); final Git resourceGit = getGit(resolved.getGitRepositoryUri()); return new File(resourceGit.getRepository().getWorkTree(), resolved.getResource()); }
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(); } }