/**
  * Gets org.eclipse.jgit.lib.Repository object for existing Git Repository.
  *
  * @param repositoryPath the path to an existing Git Repository
  * @return {@link org.eclipse.jgit.lib.Repository} object
  * @throws IOException
  */
 public static Repository getRepository(String repositoryPath) throws IOException {
   RepositoryBuilder repositoryBuilder = new RepositoryBuilder();
   repositoryBuilder.findGitDir(new File(repositoryPath));
   Repository repository = repositoryBuilder.build();
   repository.getConfig().setString(BRANCH, MASTER, MERGE, REFS_HEADS_MASTER);
   return repository;
 }
 @Override
 @After
 public void tearDown() throws Exception {
   if (src != null) src.close();
   if (dst != null) dst.close();
   super.tearDown();
 }
示例#3
0
 /**
  * Updates the file in the working tree with content and mode from an entry in the index. The new
  * content is first written to a new temporary file in the same directory as the real file. Then
  * that new file is renamed to the final filename.
  *
  * <p>TODO: this method works directly on File IO, we may need another abstraction (like
  * WorkingTreeIterator). This way we could tell e.g. Eclipse that Files in the workspace got
  * changed
  *
  * @param repo
  * @param f the file to be modified. The parent directory for this file has to exist already
  * @param entry the entry containing new mode and content
  * @param or object reader to use for checkout
  * @throws IOException
  */
 public static void checkoutEntry(
     final Repository repo, File f, DirCacheEntry entry, ObjectReader or) throws IOException {
   ObjectLoader ol = or.open(entry.getObjectId());
   File parentDir = f.getParentFile();
   parentDir.mkdirs();
   File tmpFile = File.createTempFile("._" + f.getName(), null, parentDir); // $NON-NLS-1$
   WorkingTreeOptions opt = repo.getConfig().get(WorkingTreeOptions.KEY);
   FileOutputStream rawChannel = new FileOutputStream(tmpFile);
   OutputStream channel;
   if (opt.getAutoCRLF() == AutoCRLF.TRUE) channel = new AutoCRLFOutputStream(rawChannel);
   else channel = rawChannel;
   try {
     ol.copyTo(channel);
   } finally {
     channel.close();
   }
   FS fs = repo.getFS();
   if (opt.isFileMode() && fs.supportsExecute()) {
     if (FileMode.EXECUTABLE_FILE.equals(entry.getRawMode())) {
       if (!fs.canExecute(tmpFile)) fs.setExecute(tmpFile, true);
     } else {
       if (fs.canExecute(tmpFile)) fs.setExecute(tmpFile, false);
     }
   }
   try {
     FileUtils.rename(tmpFile, f);
   } catch (IOException e) {
     throw new IOException(
         MessageFormat.format(JGitText.get().couldNotWriteFile, tmpFile.getPath(), f.getPath()));
   }
   entry.setLastModified(f.lastModified());
   if (opt.getAutoCRLF() != AutoCRLF.FALSE)
     entry.setLength(f.length()); // AutoCRLF wants on-disk-size
   else entry.setLength((int) ol.getSize());
 }
示例#4
0
  /**
   * Set the repository the formatter can load object contents from.
   *
   * <p>Once a repository has been set, the formatter must be released to ensure the internal
   * ObjectReader is able to release its resources.
   *
   * @param repository source repository holding referenced objects.
   */
  public void setRepository(Repository repository) {
    if (reader != null) reader.release();

    db = repository;
    reader = db.newObjectReader();

    ContentSource cs = ContentSource.create(reader);
    source = new ContentSource.Pair(cs, cs);

    DiffConfig dc = db.getConfig().get(DiffConfig.KEY);
    if (dc.isNoPrefix()) {
      setOldPrefix(""); // $NON-NLS-1$
      setNewPrefix(""); // $NON-NLS-1$
    }
    setDetectRenames(dc.isRenameDetectionEnabled());

    diffAlgorithm =
        DiffAlgorithm.getAlgorithm(
            db.getConfig()
                .getEnum(
                    ConfigConstants.CONFIG_DIFF_SECTION,
                    null,
                    ConfigConstants.CONFIG_KEY_ALGORITHM,
                    SupportedAlgorithm.HISTOGRAM));
  }
示例#5
0
 /**
  * Create a new in-core index representation, lock it, and read from disk.
  *
  * <p>The new index will be locked and then read before it is returned to the caller. Read
  * failures are reported as exceptions and therefore prevent the method from returning a partially
  * populated index. On read failure, the lock is released.
  *
  * @param repository repository containing the index to lock and read
  * @param indexChangedListener listener to be informed when DirCache is committed
  * @return a cache representing the contents of the specified index file (if it exists) or an
  *     empty cache if the file does not exist.
  * @throws IOException the index file is present but could not be read, or the lock could not be
  *     obtained.
  * @throws CorruptObjectException the index file is using a format or extension that this library
  *     does not support.
  * @since 2.0
  */
 public static DirCache lock(
     final Repository repository, final IndexChangedListener indexChangedListener)
     throws CorruptObjectException, IOException {
   DirCache c = lock(repository.getIndexFile(), repository.getFS(), indexChangedListener);
   c.repository = repository;
   return c;
 }
  @Test
  public void shouldUpdateTrackingBranchOnPush() throws Exception {
    makeChangesAndCommit(PROJ1);
    Repository repository = lookupRepository(repositoryFile);
    ObjectId headId = repository.resolve(Constants.HEAD);

    String trackingBranch = Constants.R_REMOTES + "origin/master";
    launchSynchronization(Constants.HEAD, trackingBranch, false);

    SWTBotView viewBot = bot.viewByTitle("Synchronize");
    SWTBotToolbarButton pushButton = viewBot.toolbarButton(UIText.GitActionContributor_Push);
    JobJoiner jobJoiner = JobJoiner.startListening(JobFamilies.PUSH, 30, TimeUnit.SECONDS);
    pushButton.click();
    jobJoiner.join();

    String destinationString = repositoryFile.getParentFile().getName() + " - " + "origin";
    SWTBotShell resultDialog =
        bot.shell(NLS.bind(UIText.PushResultDialog_title, destinationString));
    resultDialog.close();

    Repository remoteRepository = lookupRepository(childRepositoryFile);
    ObjectId masterOnRemote = remoteRepository.resolve("master");
    assertThat("Expected push to update branch on remote repository", masterOnRemote, is(headId));

    ObjectId trackingId = repository.resolve(trackingBranch);
    assertThat("Expected tracking branch to be updated", trackingId, is(headId));
  }
示例#7
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));
  }
 private static PushOperationResult push(
     Repository repository, RemoteConfig remoteConfig, boolean force, IProgressMonitor monitor)
     throws CoreException {
   try {
     if (remoteConfig == null) {
       throw new CoreException(
           createStatus(
               null,
               "Repository \"{0}\" has no remote repository configured",
               repository.toString()));
     }
     PushOperation op = createPushOperation(remoteConfig, repository, force);
     op.run(monitor);
     PushOperationResult pushResult = op.getOperationResult();
     if (hasFailedEntries(pushResult)) {
       throw new CoreException(
           EGitCoreActivator.createErrorStatus(
               NLS.bind(
                   "Could not push repository {0}: {1}",
                   repository.toString(), getErrors(pushResult)),
               null));
     }
     return pushResult;
   } catch (CoreException e) {
     throw e;
   } catch (Exception e) {
     throw new CoreException(createStatus(e, "Could not push repo {0}", repository.toString()));
   }
 }
  @Before
  public void prepare() throws Exception {
    Repository childRepository = lookupRepository(childRepositoryFile);

    Repository repository = lookupRepository(repositoryFile);
    StoredConfig config = repository.getConfig();
    RemoteConfig remoteConfig = new RemoteConfig(config, "origin");
    remoteConfig.addURI(new URIish(childRepository.getDirectory().getParentFile().toURI().toURL()));
    remoteConfig.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
    remoteConfig.update(config);

    config.setString(
        ConfigConstants.CONFIG_BRANCH_SECTION,
        "master",
        ConfigConstants.CONFIG_KEY_REMOTE,
        "origin");
    config.setString(
        ConfigConstants.CONFIG_BRANCH_SECTION,
        "master",
        ConfigConstants.CONFIG_KEY_MERGE,
        "refs/heads/master");
    config.save();

    FetchOperation fetchOperation = new FetchOperation(repository, remoteConfig, 60, false);
    fetchOperation.run(null);
  }
  /**
   * 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();
    }
  }
  /**
   * 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;
  }
 /**
  * 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();
     }
   }
 }
示例#13
0
  @Test
  public void testDeleteInWorkspace() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath =
        new Path("file").append(project.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    JSONObject clone = clone(clonePath);
    String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION);
    String contentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    Repository repository = getRepositoryForContentLocation(contentLocation);
    assertNotNull(repository);

    // delete folder with cloned repository in it
    WebRequest request = getDeleteFilesRequest(contentLocation);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // the clone is gone
    request = getGetRequest(cloneLocation);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());

    assertFalse(repository.getDirectory().exists());
  }
示例#14
0
  @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);
  }
示例#15
0
  @Override
  public void open(String repositoryPath) {

    FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
    try {
      repository =
          repositoryBuilder
              .setGitDir(new File(repositoryPath))
              .readEnvironment() // read git environment variables
              .findGitDir()
              .build();
    } catch (IOException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    }

    git = new Git(repository);
    revWalk = new RevWalk(repository);
    treeWalk = new TreeWalk(repository);
    reader = repository.newObjectReader();

    processBuilder = new ProcessBuilder();
    processBuilder.directory(new File(repository.getDirectory().toString()));

    commands = Arrays.asList("git", "log", "--numstat", "--oneline", "--max-count=1", "");

    this.repositoryPath = repository.getWorkTree().getAbsolutePath();
  }
示例#16
0
  private RefUpdate getPendingRefUpdate(Branch.NameKey destBranch) throws IntegrationException {

    if (pendingRefUpdates.containsKey(destBranch)) {
      logDebug("Access cached open branch {}: {}", destBranch.get(), openBranches.get(destBranch));
      return pendingRefUpdates.get(destBranch);
    }

    try {
      RefUpdate branchUpdate = repo.updateRef(destBranch.get());
      CodeReviewCommit branchTip;
      if (branchUpdate.getOldObjectId() != null) {
        branchTip = rw.parseCommit(branchUpdate.getOldObjectId());
      } else if (Objects.equals(repo.getFullBranch(), destBranch.get())) {
        branchTip = null;
        branchUpdate.setExpectedOldObjectId(ObjectId.zeroId());
      } else {
        throw new IntegrationException(
            "The destination branch " + destBranch.get() + " does not exist anymore.");
      }

      logDebug("Opened branch {}: {}", destBranch.get(), branchTip);
      pendingRefUpdates.put(destBranch, branchUpdate);
      openBranches.put(destBranch, branchTip);
      return branchUpdate;
    } catch (IOException e) {
      throw new IntegrationException("Cannot open branch", e);
    }
  }
示例#17
0
 @Override
 public String apply(ProjectResource rsrc)
     throws AuthException, ResourceNotFoundException, IOException {
   try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
     Ref head = repo.getRefDatabase().exactRef(Constants.HEAD);
     if (head == null) {
       throw new ResourceNotFoundException(Constants.HEAD);
     } else if (head.isSymbolic()) {
       String n = head.getTarget().getName();
       if (rsrc.getControl().controlForRef(n).isVisible()) {
         return n;
       }
       throw new AuthException("not allowed to see HEAD");
     } else if (head.getObjectId() != null) {
       try (RevWalk rw = new RevWalk(repo)) {
         RevCommit commit = rw.parseCommit(head.getObjectId());
         if (rsrc.getControl().canReadCommit(db.get(), repo, commit)) {
           return head.getObjectId().name();
         }
         throw new AuthException("not allowed to see HEAD");
       } catch (MissingObjectException | IncorrectObjectTypeException e) {
         if (rsrc.getControl().isOwner()) {
           return head.getObjectId().name();
         }
         throw new AuthException("not allowed to see HEAD");
       }
     }
     throw new ResourceNotFoundException(Constants.HEAD);
   } catch (RepositoryNotFoundException e) {
     throw new ResourceNotFoundException(rsrc.getName());
   }
 }
  @Test
  public void testInitialClone_Packed() throws Exception {
    new TestRepository<Repository>(remoteRepository).packAndPrune();

    Repository dst = createBareRepository();
    assertFalse(dst.hasObject(A_txt));

    Transport t = Transport.open(dst, remoteURI);
    ((TransportHttp) t).setUseSmartHttp(false);
    try {
      t.fetch(NullProgressMonitor.INSTANCE, mirror(master));
    } finally {
      t.close();
    }

    assertTrue(dst.hasObject(A_txt));
    assertEquals(B, dst.getRef(master).getObjectId());
    fsck(dst, B);

    List<AccessEvent> req;

    req = getRequests(loose(remoteURI, B));
    assertEquals(1, req.size());
    assertEquals("GET", req.get(0).getMethod());
    assertEquals(0, req.get(0).getParameters().size());
    assertEquals(404, req.get(0).getStatus());

    req = getRequests(join(remoteURI, "objects/info/packs"));
    assertEquals(1, req.size());
    assertEquals("GET", req.get(0).getMethod());
    assertEquals(0, req.get(0).getParameters().size());
    assertEquals(200, req.get(0).getStatus());
    assertEquals("text/plain;charset=UTF-8", req.get(0).getResponseHeader(HDR_CONTENT_TYPE));
  }
 public static boolean hasCommits(Repository repository) {
   if (repository != null && repository.getDirectory().exists()) {
     return (new File(repository.getDirectory(), "objects").list().length > 2)
         || (new File(repository.getDirectory(), "objects/pack").list().length > 0);
   }
   return false;
 }
  // 2. Get branch/commit hash for the source repo - the actual source code
  @Test
  public void existsIn() throws IOException {
    // final String repo = "binrepo-devex";
    //  final String repo = "search_raptor_binary";
    // String githubUrl = "https://github.scm.corp.ebay.com/api/v3";
    // String accessToken = "1cf7d9792235b8592eda18bd7dcc2de37f99b3bc";

    final String path = "D:\\dev\\devex\\binrepo-devex\\.git";

    File gitDir = new File(path);
    org.eclipse.jgit.lib.Repository repository =
        new org.eclipse.jgit.storage.file.FileRepository(gitDir);
    String branch = repository.getBranch();
    System.out.println(branch);

    RevWalk revWalk = new RevWalk(repository);
    // Pop the most recent commit off from RevWalk
    // RevCommit commit = revWalk.next(); returns null :-(
    // System.out.println(commit);

    ObjectId resolve = repository.resolve(Constants.HEAD);
    RevCommit commit = revWalk.parseCommit(resolve);
    String commitHash = commit.getName();
    System.out.println(commitHash + "\t" + commit.getFullMessage());

    // RefDatabase refDatabase = repository.getRefDatabase();

  }
  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);
    }
  }
  @Override
  public PageData getRevisionData(FileSystemPage page, String label) {
    // Workaround for CachingPage
    if (label == null) {
      return persistence.getRevisionData(page, null);
    }
    String content, propertiesXml;
    RevCommit revCommit;
    Repository repository = getRepository(page);

    try {
      String fileSystemPath = getPath(page, repository);
      ObjectId rev = repository.resolve(label);
      RevWalk walk = new RevWalk(repository);
      revCommit = walk.parseCommit(rev);

      content = getRepositoryContent(repository, revCommit, fileSystemPath + "/" + contentFilename);
      propertiesXml =
          getRepositoryContent(repository, revCommit, fileSystemPath + "/" + propertiesFilename);
    } catch (IOException e) {
      throw new RuntimeException("Unable to get data for revision " + label, e);
    }

    final PageData pageData = new PageData(page);
    pageData.setContent(content);
    pageData.setProperties(
        parsePropertiesXml(propertiesXml, revCommit.getAuthorIdent().getWhen().getTime()));
    return pageData;
  }
  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();
    }
  }
示例#24
0
 /** @param repository */
 public IndexDiffCacheEntry(Repository repository) {
   this.repository = repository;
   indexChangedListenerHandle =
       repository
           .getListenerList()
           .addIndexChangedListener(
               new IndexChangedListener() {
                 public void onIndexChanged(IndexChangedEvent event) {
                   refreshIndexDelta();
                 }
               });
   refsChangedListenerHandle =
       repository
           .getListenerList()
           .addRefsChangedListener(
               new RefsChangedListener() {
                 public void onRefsChanged(RefsChangedEvent event) {
                   scheduleReloadJob("RefsChanged"); // $NON-NLS-1$
                 }
               });
   scheduleReloadJob("IndexDiffCacheEntry construction"); // $NON-NLS-1$
   createResourceChangeListener();
   if (!repository.isBare()) {
     try {
       lastIndex = repository.readDirCache();
     } catch (IOException ex) {
       Activator.error(
           MessageFormat.format(
               CoreText.IndexDiffCacheEntry_errorCalculatingIndexDelta, repository),
           ex);
     }
   }
 }
 /**
  * Returns a RefModel for the refs/meta/gitblit/tickets branch in the repository. If the branch
  * can not be found, null is returned.
  *
  * @return a refmodel for the gitblit tickets branch or null
  */
 private RefModel getTicketsBranch(Repository db) {
   List<RefModel> refs = JGitUtils.getRefs(db, "refs/");
   Ref oldRef = null;
   for (RefModel ref : refs) {
     if (ref.reference.getName().equals(BRANCH)) {
       return ref;
     } else if (ref.reference.getName().equals("refs/gitblit/tickets")) {
       oldRef = ref.reference;
     }
   }
   if (oldRef != null) {
     // rename old ref to refs/meta/gitblit/tickets
     RefRename cmd;
     try {
       cmd = db.renameRef(oldRef.getName(), BRANCH);
       cmd.setRefLogIdent(new PersonIdent("Gitblit", "gitblit@localhost"));
       cmd.setRefLogMessage("renamed " + oldRef.getName() + " => " + BRANCH);
       Result res = cmd.rename();
       switch (res) {
         case RENAMED:
           log.info(db.getDirectory() + " " + cmd.getRefLogMessage());
           return getTicketsBranch(db);
         default:
           log.error(
               "failed to rename " + oldRef.getName() + " => " + BRANCH + " (" + res.name() + ")");
       }
     } catch (IOException e) {
       log.error("failed to rename tickets branch", e);
     }
   }
   return null;
 }
  @Test
  public void testInitialClone_Small() throws Exception {
    Repository dst = createBareRepository();
    assertFalse(dst.hasObject(A_txt));

    Transport t = Transport.open(dst, remoteURI);
    ((TransportHttp) t).setUseSmartHttp(false);
    try {
      t.fetch(NullProgressMonitor.INSTANCE, mirror(master));
    } finally {
      t.close();
    }

    assertTrue(dst.hasObject(A_txt));
    assertEquals(B, dst.getRef(master).getObjectId());
    fsck(dst, B);

    List<AccessEvent> loose = getRequests(loose(remoteURI, A_txt));
    assertEquals(1, loose.size());
    assertEquals("GET", loose.get(0).getMethod());
    assertEquals(0, loose.get(0).getParameters().size());
    assertEquals(200, loose.get(0).getStatus());
    assertEquals(
        "application/x-git-loose-object", loose.get(0).getResponseHeader(HDR_CONTENT_TYPE));
  }
示例#27
0
  /** Gets the commit log and stores it in a project property as configured. */
  @TaskAction
  public void reset() {
    final LogCommand cmd = getGit().log();
    Repository repo = getGit().getRepository();
    if (includes != null) {
      for (String include : includes) {
        try {
          ObjectId commit = repo.resolve(include);
          if (commit == null) {
            throw new GradleException("No commit found for revision string: " + include);
          } else {
            cmd.add(commit);
          }
        } catch (AmbiguousObjectException e) {
          throw new GradleException("Revision string is ambiguous: " + include, e);
        } catch (MissingObjectException e) {
          throw new GradleException("Commit could not be found in repository: " + include, e);
        } catch (IncorrectObjectTypeException e) {
          throw new GradleException("Revision string did not point to a commit: " + include, e);
        } catch (IOException e) {
          throw new GradleException("Problem resolving revision string: " + include, e);
        }
      }
    }
    if (excludes != null) {
      for (String exclude : excludes) {
        try {
          ObjectId commit = repo.resolve(exclude);
          if (commit == null) {
            throw new GradleException("No commit found for revision string: " + exclude);
          } else {
            cmd.add(commit);
          }
        } catch (AmbiguousObjectException e) {
          throw new GradleException("Revision string is ambiguous: " + exclude, e);
        } catch (MissingObjectException e) {
          throw new GradleException("Commit could not be found in repository: " + exclude, e);
        } catch (IncorrectObjectTypeException e) {
          throw new GradleException("Revision string did not point to a commit: " + exclude, e);
        } catch (IOException e) {
          throw new GradleException("Problem resolving revision string: " + exclude, e);
        }
      }
    }
    cmd.setSkip(skipCommits);
    cmd.setMaxCount(maxCommits);

    try {
      Iterable<RevCommit> commits = cmd.call();
      List<Commit> tempLog = new ArrayList<Commit>();
      for (RevCommit commit : commits) {
        tempLog.add(GitUtil.revCommitToCommit(commit));
      }
      this.log = Collections.unmodifiableList(tempLog);
    } catch (GitAPIException e) {
      throw new GradleException("Problem with log.", e);
    }
    // TODO add progress monitor to log progress to Gradle status bar
  }
示例#28
0
 @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);
   }
 }
示例#29
0
 CriticalResource get(Repository repo) {
   CriticalResource cr = locks.get(repo.getDirectory());
   if (cr == null) {
     cr = new CR();
     locks.put(repo.getDirectory(), cr);
   }
   return cr;
 }
示例#30
0
  @Test
  public void testShouldAutomagicallyDetectGitDirectory() throws Exception {
    Repository r = createWorkRepository();
    File d = new File(r.getDirectory(), "sub-dir");
    FileUtils.mkdir(d);

    assertEquals(r.getDirectory(), new FileRepositoryBuilder().findGitDir(d).getGitDir());
  }