コード例 #1
0
 @Override
 @After
 public void tearDown() throws Exception {
   if (src != null) src.close();
   if (dst != null) dst.close();
   super.tearDown();
 }
コード例 #2
0
  @Override
  @After
  public void tearDown() throws Exception {
    if (repository1 != null) repository1.close();
    if (repository2 != null) repository2.close();
    if (repository3 != null) repository3.close();

    if (workdir.exists()) FileUtils.delete(workdir, FileUtils.RECURSIVE | FileUtils.RETRY);
    if (workdir2.exists()) FileUtils.delete(workdir2, FileUtils.RECURSIVE | FileUtils.RETRY);
    if (workdir3.exists()) FileUtils.delete(workdir3, FileUtils.RECURSIVE | FileUtils.RETRY);
    super.tearDown();
  }
コード例 #3
0
  /**
   * Assigns a new ticket id.
   *
   * @param repository
   * @return a new long id
   */
  @Override
  public synchronized long assignNewId(RepositoryModel repository) {
    long newId = 0L;
    Repository db = repositoryManager.getRepository(repository.name);
    try {
      if (getTicketsBranch(db) == null) {
        createTicketsBranch(db);
      }

      // identify current highest ticket id by scanning the paths in the tip tree
      if (!lastAssignedId.containsKey(repository.name)) {
        lastAssignedId.put(repository.name, new AtomicLong(0));
      }
      AtomicLong lastId = lastAssignedId.get(repository.name);
      if (lastId.get() <= 0) {
        Set<Long> ids = getIds(repository);
        for (long id : ids) {
          if (id > lastId.get()) {
            lastId.set(id);
          }
        }
      }

      // assign the id and touch an empty journal to hold it's place
      newId = lastId.incrementAndGet();
      String journalPath = toTicketPath(newId) + "/" + JOURNAL;
      writeTicketsFile(db, journalPath, "", "gitblit", "assigned id #" + newId);
    } finally {
      db.close();
    }
    return newId;
  }
コード例 #4
0
 /**
  * Returns the assigned ticket ids.
  *
  * @return the assigned ticket ids
  */
 @Override
 public synchronized Set<Long> getIds(RepositoryModel repository) {
   Repository db = repositoryManager.getRepository(repository.name);
   try {
     if (getTicketsBranch(db) == null) {
       return Collections.emptySet();
     }
     Set<Long> ids = new TreeSet<Long>();
     List<PathModel> paths = JGitUtils.getDocuments(db, Arrays.asList("json"), BRANCH);
     for (PathModel path : paths) {
       String name = path.name.substring(path.name.lastIndexOf('/') + 1);
       if (!JOURNAL.equals(name)) {
         continue;
       }
       String tid = path.path.split("/")[2];
       long ticketId = Long.parseLong(tid);
       ids.add(ticketId);
     }
     return ids;
   } finally {
     if (db != null) {
       db.close();
     }
   }
 }
コード例 #5
0
ファイル: CleanCommandTest.java プロジェクト: spearce/jgit
  @Test
  public void testCleanDirsWithSubmodule() throws Exception {
    SubmoduleAddCommand command = new SubmoduleAddCommand(db);
    String path = "sub";
    command.setPath(path);
    String uri = db.getDirectory().toURI().toString();
    command.setURI(uri);
    Repository repo = command.call();
    repo.close();

    Status beforeCleanStatus = git.status().call();
    assertTrue(beforeCleanStatus.getAdded().contains(DOT_GIT_MODULES));
    assertTrue(beforeCleanStatus.getAdded().contains(path));

    Set<String> cleanedFiles = git.clean().setCleanDirectories(true).call();

    // The submodule should not be cleaned.
    assertTrue(!cleanedFiles.contains(path + "/"));

    assertTrue(cleanedFiles.contains("File2.txt"));
    assertTrue(cleanedFiles.contains("File3.txt"));
    assertTrue(!cleanedFiles.contains("sub-noclean/File1.txt"));
    assertTrue(cleanedFiles.contains("sub-noclean/File2.txt"));
    assertTrue(cleanedFiles.contains("sub-clean/"));
    assertTrue(cleanedFiles.size() == 4);
  }
コード例 #6
0
  public String getProjectDescription(final Project.NameKey name)
      throws RepositoryNotFoundException, IOException {
    final Repository e = openRepository(name);
    try {
      final File d = new File(e.getDirectory(), "description");

      String description;
      try {
        description = RawParseUtils.decode(IO.readFully(d));
      } catch (FileNotFoundException err) {
        return null;
      }

      if (description != null) {
        description = description.trim();
        if (description.isEmpty()) {
          description = null;
        }
        if (UNNAMED.equals(description)) {
          description = null;
        }
      }
      return description;
    } finally {
      e.close();
    }
  }
コード例 #7
0
  public void setProjectDescription(final Project.NameKey name, final String description) {
    // Update git's description file, in case gitweb is being used
    //
    try {
      final Repository e;
      final LockFile f;

      e = openRepository(name);
      try {
        f = new LockFile(new File(e.getDirectory(), "description"), FS.DETECTED);
        if (f.lock()) {
          String d = description;
          if (d != null) {
            d = d.trim();
            if (d.length() > 0) {
              d += "\n";
            }
          } else {
            d = "";
          }
          f.write(Constants.encode(d));
          f.commit();
        }
      } finally {
        e.close();
      }
    } catch (RepositoryNotFoundException e) {
      log.error("Cannot update description for " + name, e);
    } catch (IOException e) {
      log.error("Cannot update description for " + name, e);
    }
  }
コード例 #8
0
  /**
   * Retrieves the specified attachment from a ticket.
   *
   * @param repository
   * @param ticketId
   * @param filename
   * @return an attachment, if found, null otherwise
   */
  @Override
  public Attachment getAttachment(RepositoryModel repository, long ticketId, String filename) {
    if (ticketId <= 0L) {
      return null;
    }

    // deserialize the ticket model so that we have the attachment metadata
    TicketModel ticket = getTicket(repository, ticketId);
    Attachment attachment = ticket.getAttachment(filename);

    // attachment not found
    if (attachment == null) {
      return null;
    }

    // retrieve the attachment content
    Repository db = repositoryManager.getRepository(repository.name);
    try {
      String attachmentPath = toAttachmentPath(ticketId, attachment.name);
      RevTree tree = JGitUtils.getCommit(db, BRANCH).getTree();
      byte[] content = JGitUtils.getByteContent(db, tree, attachmentPath, false);
      attachment.content = content;
      attachment.size = content.length;
      return attachment;
    } finally {
      db.close();
    }
  }
コード例 #9
0
  private boolean handleDelete(
      HttpServletRequest request, HttpServletResponse response, String pathString)
      throws GitAPIException, CoreException, IOException, ServletException {
    IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
    // expected path format is /file/{workspaceId}/{projectId}[/{directoryPath}]
    if (path.segment(0).equals("file") && path.segmentCount() > 2) { // $NON-NLS-1$

      // make sure a clone is addressed
      WebProject webProject = GitUtils.projectFromPath(path);
      if (webProject != null && isAccessAllowed(request.getRemoteUser(), webProject)) {
        File gitDir = GitUtils.getGitDirs(path, Traverse.CURRENT).values().iterator().next();
        Repository repo = new FileRepository(gitDir);
        repo.close();
        FileUtils.delete(repo.getWorkTree(), FileUtils.RECURSIVE | FileUtils.RETRY);
        if (path.segmentCount() == 3)
          return statusHandler.handleRequest(
              request, response, removeProject(request.getRemoteUser(), webProject));
        return true;
      }
      String msg = NLS.bind("Nothing found for the given ID: {0}", path);
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
    }
    String msg = NLS.bind("Invalid delete request {0}", pathString);
    return statusHandler.handleRequest(
        request,
        response,
        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
  }
コード例 #10
0
  private static ChangeKind getChangeKindInternal(
      ChangeKindCache cache,
      ReviewDb db,
      Change change,
      PatchSet patch,
      ChangeData.Factory changeDataFactory,
      ProjectCache projectCache,
      GitRepositoryManager repoManager) {
    Repository repo = null;
    // TODO - dborowitz: add NEW_CHANGE type for default.
    ChangeKind kind = ChangeKind.REWORK;
    // Trivial case: if we're on the first patch, we don't need to open
    // the repository.
    if (patch.getId().get() > 1) {
      try {
        ProjectState projectState = projectCache.checkedGet(change.getProject());

        repo = repoManager.openRepository(change.getProject());

        ChangeData cd = changeDataFactory.create(db, change);
        Collection<PatchSet> patchSetCollection = cd.patches();
        PatchSet priorPs = patch;
        for (PatchSet ps : patchSetCollection) {
          if (ps.getId().get() < patch.getId().get()
              && (ps.getId().get() > priorPs.getId().get() || priorPs == patch)) {
            // We only want the previous patch set, so walk until the last one
            priorPs = ps;
          }
        }

        // If we still think the previous patch is the current patch,
        // we only have one patch set.  Return the default.
        // This can happen if a user creates a draft, uploads a second patch,
        // and deletes the draft.
        if (priorPs != patch) {
          kind =
              cache.getChangeKind(
                  projectState,
                  repo,
                  ObjectId.fromString(priorPs.getRevision().get()),
                  ObjectId.fromString(patch.getRevision().get()));
        }
      } catch (IOException | OrmException e) {
        // Do nothing; assume we have a complex change
        log.warn(
            "Unable to get change kind for patchSet "
                + patch.getPatchSetId()
                + "of change "
                + change.getChangeId(),
            e);
      } finally {
        if (repo != null) {
          repo.close();
        }
      }
    }
    return kind;
  }
コード例 #11
0
  @Override
  public void close() {

    repository.close();
    git.close();
    treeWalk.close();
    revWalk.close();
    reader.close();
  }
コード例 #12
0
ファイル: DiffUtilsTest.java プロジェクト: noelmac/gitblit
 @Test
 public void testBlame() throws Exception {
   Repository repository = GitBlitSuite.getHelloworldRepository();
   List<AnnotatedLine> lines =
       DiffUtils.blame(repository, "java.java", "1d0c2933a4ae69c362f76797d42d6bd182d05176");
   repository.close();
   assertTrue(lines.size() > 0);
   assertEquals("c6d31dccf5cc75e8e46299fc62d38f60ec6d41e0", lines.get(0).commitId);
 }
コード例 #13
0
 /**
  * Releases the repository acquired via {@link #add} or {@link #get} method. Decrements an
  * openCounter for the repository and if it reaches 0 repository is closed and removed from the
  * cache. Does nothing if repository is not present found in the cache.
  *
  * @param db repository to release
  */
 synchronized void release(@NotNull Repository db) {
   RepositoryCache.FileKey key = RepositoryCache.FileKey.exact(db.getDirectory(), FS.DETECTED);
   CachedRepository cachedRepository = myRepositories.get(key);
   if (cachedRepository != null
       && cachedRepository.getRepository() == db
       && cachedRepository.dec() == 0) {
     myRepositories.remove(key);
     db.close();
   }
 }
コード例 #14
0
 @Override
 public Map<String, RepositoryDescription> listRepositories(String prefix, Set<String> branches)
     throws IOException {
   Map<String, RepositoryDescription> repos = Maps.newTreeMap(US_COLLATOR);
   for (Repository repo : scanRepositories(basePath, prefix, req)) {
     repos.put(getRepositoryName(repo), buildDescription(repo, branches));
     repo.close();
   }
   return repos;
 }
コード例 #15
0
ファイル: DataGit.java プロジェクト: eclipse/emf.compare
  public void dispose() {
    comparison = null;
    for (ResourceSet rs : resourceSets) {
      EList<Resource> resources = rs.getResources();
      for (Resource resource : resources) {
        TreeIterator<EObject> allContents = EcoreUtil.getAllProperContents(resource, false);
        while (allContents.hasNext()) {
          final EObject next = allContents.next();
          next.eAdapters().clear();
        }
        resource.eAdapters().clear();
      }

      rs.getResources().clear();
      rs.eAdapters().clear();
    }

    resourceSets = null;

    Job cleanJob =
        new Job("ClearWorkspace") {
          @Override
          protected IStatus run(IProgressMonitor monitor) {
            try {
              // Close & delete projects from workspace
              IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
              for (IProject project : projects) {
                project.close(new NullProgressMonitor());
                project.delete(false, new NullProgressMonitor());
              }
            } catch (CoreException e) {
              Throwables.propagate(e);
            }
            return Status.OK_STATUS;
          }
        };
    cleanJob.schedule();
    try {
      cleanJob.join();
    } catch (InterruptedException e) {
      Throwables.propagate(e);
    }

    if (repository != null) {
      repository.close();
      repository = null;
    }
    for (Runnable disposer : disposers) {
      disposer.run();
    }
    disposers.clear();

    // Delete repository from temp directory
    GitUtil.deleteRepo(repoFile);
  }
コード例 #16
0
 public Git load() throws IOException {
   Repository repository = new RepositoryBuilder().findGitDir(this.sourceDirectory).build();
   try {
     Git.Head head = getHead(repository);
     String branch = getBranch(repository);
     List<Git.Remote> remotes = getRemotes(repository);
     return new Git(head, branch, remotes);
   } finally {
     repository.close();
   }
 }
コード例 #17
0
ファイル: MergeOp.java プロジェクト: web1992/gerrit
 private void closeRepository() {
   if (inserter != null) {
     inserter.close();
   }
   if (rw != null) {
     rw.close();
   }
   if (repo != null) {
     repo.close();
   }
 }
コード例 #18
0
ファイル: DiffUtilsTest.java プロジェクト: noelmac/gitblit
 @Test
 public void testPlainFileDiff() throws Exception {
   Repository repository = GitBlitSuite.getHelloworldRepository();
   RevCommit commit = JGitUtils.getCommit(repository, "1d0c2933a4ae69c362f76797d42d6bd182d05176");
   String diff = DiffUtils.getDiff(repository, commit, "java.java", DiffOutputType.PLAIN).content;
   repository.close();
   assertTrue(diff != null && diff.length() > 0);
   String expected =
       "-		system.out.println(\"Hello World\");\n+		System.out.println(\"Hello World\"";
   assertTrue(diff.indexOf(expected) > -1);
 }
コード例 #19
0
ファイル: DiffUtilsTest.java プロジェクト: noelmac/gitblit
 @Test
 public void testFilePatch() throws Exception {
   Repository repository = GitBlitSuite.getHelloworldRepository();
   RevCommit commit = JGitUtils.getCommit(repository, "1d0c2933a4ae69c362f76797d42d6bd182d05176");
   String patch = DiffUtils.getCommitPatch(repository, null, commit, "java.java");
   repository.close();
   assertTrue(patch != null && patch.length() > 0);
   String expected =
       "-		system.out.println(\"Hello World\");\n+		System.out.println(\"Hello World\"";
   assertTrue(patch.indexOf(expected) > -1);
 }
コード例 #20
0
 private LabelTypes getLabelTypes() throws Exception {
   db.create();
   ProjectConfig c = new ProjectConfig(allProjects);
   Repository repo = repoManager.openRepository(allProjects);
   try {
     c.load(repo);
     return new LabelTypes(ImmutableList.copyOf(c.getLabelSections().values()));
   } finally {
     repo.close();
   }
 }
コード例 #21
0
ファイル: DiffUtilsTest.java プロジェクト: noelmac/gitblit
 @Test
 public void testArbitraryCommitDiff() throws Exception {
   Repository repository = GitBlitSuite.getHelloworldRepository();
   RevCommit baseCommit =
       JGitUtils.getCommit(repository, "8baf6a833b5579384d9b9ceb8a16b5d0ea2ec4ca");
   RevCommit commit = JGitUtils.getCommit(repository, "1d0c2933a4ae69c362f76797d42d6bd182d05176");
   String diff = DiffUtils.getDiff(repository, baseCommit, commit, DiffOutputType.PLAIN).content;
   repository.close();
   assertTrue(diff != null && diff.length() > 0);
   String expected =
       "-		system.out.println(\"Hello World\");\n+		System.out.println(\"Hello World\"";
   assertTrue(diff.indexOf(expected) > -1);
 }
コード例 #22
0
  @After
  public void tearDown() throws Exception {

    Thread.sleep(1000); // FIXME: We need a good way to wait for things to settle

    RepositoryProvider.unmap(project);
    RepositoryProvider.unmap(project2);

    GitProjectData.delete(project);
    GitProjectData.delete(project2);

    project.delete(true, true, null);
    project2.delete(true, true, null);

    repository.close();
    repository2.close();

    org.eclipse.egit.core.Activator.getDefault().getRepositoryCache().clear();

    FileUtils.delete(gitDir, FileUtils.RECURSIVE);
    // gitDir2 is inside project, already gone
  }
コード例 #23
0
  @Test
  public void test() throws Exception {
    // prepare a new folder
    File localPath = File.createTempFile("TestGitRepository", "");
    localPath.delete();

    // create the directory
    Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git"));
    repository.create(false);

    System.out.println("Having repository: " + repository.getDirectory());

    repository.close();
  }
コード例 #24
0
 /**
  * Retrieves the journal for the ticket.
  *
  * @param repository
  * @param ticketId
  * @return a journal, if it exists, otherwise null
  */
 @Override
 protected List<Change> getJournalImpl(RepositoryModel repository, long ticketId) {
   Repository db = repositoryManager.getRepository(repository.name);
   try {
     List<Change> changes = getJournal(db, ticketId);
     if (ArrayUtils.isEmpty(changes)) {
       log.warn("Empty journal for {}:{}", repository, ticketId);
       return null;
     }
     return changes;
   } finally {
     db.close();
   }
 }
コード例 #25
0
  public static void main(String[] args)
      throws IOException, InvalidRefNameException, GitAPIException {
    Repository repository = CookbookHelper.openJGitCookbookRepository();

    Git git = new Git(repository);
    Iterable<RevCommit> commits = git.log().all().call();
    int count = 0;
    for (RevCommit commit : commits) {
      System.out.println("LogCommit: " + commit);
      count++;
    }
    System.out.println(count);

    repository.close();
  }
コード例 #26
0
 // Git Client implementation throws away committer date info so we have to do this manually..
 // Copied from JGitAPIImpl.commit(String message)
 private void commit(String message, PersonIdent author, PersonIdent committer) {
   Repository repo = null;
   try {
     repo = testGitClient.getRepository();
     CommitCommand cmd = Git.wrap(repo).commit().setMessage(message);
     if (author != null) cmd.setAuthor(author);
     if (committer != null)
       // cmd.setCommitter(new PersonIdent(committer,new Date()));
       cmd.setCommitter(committer);
     cmd.call();
   } catch (GitAPIException e) {
     throw new GitException(e);
   } finally {
     if (repo != null) repo.close();
   }
 }
コード例 #27
0
 /**
  * Ensures that we have a ticket for this ticket id.
  *
  * @param repository
  * @param ticketId
  * @return true if the ticket exists
  */
 @Override
 public boolean hasTicket(RepositoryModel repository, long ticketId) {
   boolean hasTicket = false;
   Repository db = repositoryManager.getRepository(repository.name);
   try {
     RefModel ticketsBranch = getTicketsBranch(db);
     if (ticketsBranch == null) {
       return false;
     }
     String ticketPath = toTicketPath(ticketId);
     RevCommit tip = JGitUtils.getCommit(db, BRANCH);
     hasTicket = !JGitUtils.getFilesInPath(db, ticketPath, tip).isEmpty();
   } finally {
     db.close();
   }
   return hasTicket;
 }
コード例 #28
0
 @Override
 protected boolean deleteAllImpl(RepositoryModel repository) {
   Repository db = repositoryManager.getRepository(repository.name);
   try {
     RefModel branch = getTicketsBranch(db);
     if (branch != null) {
       return JGitUtils.deleteBranchRef(db, BRANCH);
     }
     return true;
   } catch (Exception e) {
     log.error(null, e);
   } finally {
     if (db != null) {
       db.close();
     }
   }
   return false;
 }
コード例 #29
0
ファイル: ExistingOrNewPage.java プロジェクト: blizzy78/egit
 private void fillTreeItemWithGitDirectory(
     RepositoryMapping m, TreeItem treeItem, boolean isAlternative) {
   if (m.getGitDir() == null)
     treeItem.setText(2, UIText.ExistingOrNewPage_SymbolicValueEmptyMapping);
   else {
     IPath relativePath = new Path(m.getGitDir());
     if (isAlternative) {
       IPath withoutLastSegment = relativePath.removeLastSegments(1);
       IPath path;
       if (withoutLastSegment.isEmpty()) path = Path.fromPortableString("."); // $NON-NLS-1$
       else path = withoutLastSegment;
       treeItem.setText(0, path.toString());
     }
     treeItem.setText(2, relativePath.toOSString());
     try {
       IProject project = m.getContainer().getProject();
       Repository repo =
           new RepositoryBuilder().setGitDir(m.getGitDirAbsolutePath().toFile()).build();
       File workTree = repo.getWorkTree();
       IPath workTreePath = Path.fromOSString(workTree.getAbsolutePath());
       if (workTreePath.isPrefixOf(project.getLocation())) {
         IPath makeRelativeTo = project.getLocation().makeRelativeTo(workTreePath);
         String repoRelativePath =
             makeRelativeTo.append("/.project").toPortableString(); // $NON-NLS-1$
         ObjectId headCommitId = repo.resolve(Constants.HEAD);
         if (headCommitId != null) {
           // Not an empty repo
           RevWalk revWalk = new RevWalk(repo);
           RevCommit headCommit = revWalk.parseCommit(headCommitId);
           RevTree headTree = headCommit.getTree();
           TreeWalk projectInRepo = TreeWalk.forPath(repo, repoRelativePath, headTree);
           if (projectInRepo != null) {
             // the .project file is tracked by this repo
             treeItem.setChecked(true);
           }
           revWalk.dispose();
         }
       }
       repo.close();
     } catch (IOException e1) {
       Activator.logError(UIText.ExistingOrNewPage_FailedToDetectRepositoryMessage, e1);
     }
   }
 }
コード例 #30
0
ファイル: ShowLog.java プロジェクト: noamkachko/jgit-cookbook
  public static void main(String[] args) throws IOException, GitAPIException {
    Repository repository = CookbookHelper.openJGitCookbookRepository();

    Iterable<RevCommit> logs = new Git(repository).log().all().call();
    int count = 0;
    for (RevCommit rev : logs) {
      System.out.println(
          "Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
      count++;
    }
    System.out.println("Had " + count + " commits overall on current branch");

    logs =
        new Git(repository)
            .log()
            // for all log.all()
            .addPath("README.md")
            .call();
    count = 0;
    for (RevCommit rev : logs) {
      System.out.println(
          "Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
      count++;
    }
    System.out.println("Had " + count + " commits on README.md");

    logs =
        new Git(repository)
            .log()
            // for all log.all()
            .addPath("pom.xml")
            .call();
    count = 0;
    for (RevCommit rev : logs) {
      System.out.println(
          "Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
      count++;
    }
    System.out.println("Had " + count + " commits on pom.xml");

    repository.close();
  }