@Override
 public Image getImage(Object element) {
   RepositoryTreeNode node = (RepositoryTreeNode) element;
   if (node.getType() == RepositoryTreeNodeType.TAG) {
     // determine if we have a lightweight tag and
     // use the corresponding icon
     RevObject any;
     try {
       ObjectId id = node.getRepository().resolve(((Ref) node.getObject()).getName());
       if (id == null) return null;
       any = new RevWalk(node.getRepository()).parseAny(id);
     } catch (MissingObjectException e) {
       Activator.logError(e.getMessage(), e);
       return null;
     } catch (IOException e) {
       Activator.logError(e.getMessage(), e);
       return null;
     }
     if (any instanceof RevCommit)
       // lightweight tag
       return decorateImage(lightweightTagImage, element);
     else
       // annotated or signed tag
       return decorateImage(node.getType().getIcon(), element);
   } else return decorateImage(node.getType().getIcon(), element);
 }
  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);
    }
  }
  @Test
  public void testUsingHiddenDeltaBaseFails() throws Exception {
    byte[] delta = {0x1, 0x1, 0x1, 'c'};
    TestRepository<Repository> s = new TestRepository<Repository>(src);
    RevCommit N =
        s.commit()
            .parent(B)
            .add("q", s.blob(BinaryDelta.apply(dst.open(b).getCachedBytes(), delta)))
            .create();

    final TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024);
    packHeader(pack, 3);
    copy(pack, src.open(N));
    copy(pack, src.open(s.parseBody(N).getTree()));
    pack.write((Constants.OBJ_REF_DELTA) << 4 | 4);
    b.copyRawTo(pack);
    deflate(pack, delta);
    digest(pack);

    final TemporaryBuffer.Heap inBuf = new TemporaryBuffer.Heap(1024);
    final PacketLineOut inPckLine = new PacketLineOut(inBuf);
    inPckLine.writeString(
        ObjectId.zeroId().name()
            + ' '
            + N.name()
            + ' '
            + "refs/heads/s"
            + '\0'
            + BasePackPushConnection.CAPABILITY_REPORT_STATUS);
    inPckLine.end();
    pack.writeTo(inBuf, PM);

    final TemporaryBuffer.Heap outBuf = new TemporaryBuffer.Heap(1024);
    final ReceivePack rp = new ReceivePack(dst);
    rp.setCheckReceivedObjects(true);
    rp.setCheckReferencedObjectsAreReachable(true);
    rp.setAdvertiseRefsHook(new HidePrivateHook());
    try {
      receive(rp, inBuf, outBuf);
      fail("Expected UnpackException");
    } catch (UnpackException failed) {
      Throwable err = failed.getCause();
      assertTrue(err instanceof MissingObjectException);
      MissingObjectException moe = (MissingObjectException) err;
      assertEquals(b, moe.getObjectId());
    }

    final PacketLineIn r = asPacketLineIn(outBuf);
    String master = r.readString();
    int nul = master.indexOf('\0');
    assertTrue("has capability list", nul > 0);
    assertEquals(B.name() + ' ' + R_MASTER, master.substring(0, nul));
    assertSame(PacketLineIn.END, r.readString());

    assertEquals("unpack error Missing blob " + b.name(), r.readString());
    assertEquals("ng refs/heads/s n/a (unpacker error)", r.readString());
    assertSame(PacketLineIn.END, r.readString());
  }
  @Test
  public void testUsingUnknownBlobFails() throws Exception {
    // Try to use the 'n' blob that is not on the server.
    //
    TestRepository<Repository> s = new TestRepository<Repository>(src);
    RevBlob n = s.blob("n");
    RevCommit N = s.commit().parent(B).add("q", n).create();

    // But don't include it in the pack.
    //
    final TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024);
    packHeader(pack, 2);
    copy(pack, src.open(N));
    copy(pack, src.open(s.parseBody(N).getTree()));
    digest(pack);

    final TemporaryBuffer.Heap inBuf = new TemporaryBuffer.Heap(1024);
    final PacketLineOut inPckLine = new PacketLineOut(inBuf);
    inPckLine.writeString(
        ObjectId.zeroId().name()
            + ' '
            + N.name()
            + ' '
            + "refs/heads/s"
            + '\0'
            + BasePackPushConnection.CAPABILITY_REPORT_STATUS);
    inPckLine.end();
    pack.writeTo(inBuf, PM);

    final TemporaryBuffer.Heap outBuf = new TemporaryBuffer.Heap(1024);
    final ReceivePack rp = new ReceivePack(dst);
    rp.setCheckReceivedObjects(true);
    rp.setCheckReferencedObjectsAreReachable(true);
    rp.setAdvertiseRefsHook(new HidePrivateHook());
    try {
      receive(rp, inBuf, outBuf);
      fail("Expected UnpackException");
    } catch (UnpackException failed) {
      Throwable err = failed.getCause();
      assertTrue(err instanceof MissingObjectException);
      MissingObjectException moe = (MissingObjectException) err;
      assertEquals(n, moe.getObjectId());
    }

    final PacketLineIn r = asPacketLineIn(outBuf);
    String master = r.readString();
    int nul = master.indexOf('\0');
    assertTrue("has capability list", nul > 0);
    assertEquals(B.name() + ' ' + R_MASTER, master.substring(0, nul));
    assertSame(PacketLineIn.END, r.readString());

    assertEquals("unpack error Missing blob " + n.name(), r.readString());
    assertEquals("ng refs/heads/s n/a (unpacker error)", r.readString());
    assertSame(PacketLineIn.END, r.readString());
  }
  @Test
  public void testCreateBranchAtHiddenCommitFails() throws Exception {
    final TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(64);
    packHeader(pack, 0);
    digest(pack);

    final TemporaryBuffer.Heap inBuf = new TemporaryBuffer.Heap(256);
    final PacketLineOut inPckLine = new PacketLineOut(inBuf);
    inPckLine.writeString(
        ObjectId.zeroId().name()
            + ' '
            + P.name()
            + ' '
            + "refs/heads/s"
            + '\0'
            + BasePackPushConnection.CAPABILITY_REPORT_STATUS);
    inPckLine.end();
    pack.writeTo(inBuf, PM);

    final TemporaryBuffer.Heap outBuf = new TemporaryBuffer.Heap(1024);
    final ReceivePack rp = new ReceivePack(dst);
    rp.setCheckReceivedObjects(true);
    rp.setCheckReferencedObjectsAreReachable(true);
    rp.setAdvertiseRefsHook(new HidePrivateHook());
    try {
      receive(rp, inBuf, outBuf);
      fail("Expected UnpackException");
    } catch (UnpackException failed) {
      Throwable err = failed.getCause();
      assertTrue(err instanceof MissingObjectException);
      MissingObjectException moe = (MissingObjectException) err;
      assertEquals(P, moe.getObjectId());
    }

    final PacketLineIn r = asPacketLineIn(outBuf);
    String master = r.readString();
    int nul = master.indexOf('\0');
    assertTrue("has capability list", nul > 0);
    assertEquals(B.name() + ' ' + R_MASTER, master.substring(0, nul));
    assertSame(PacketLineIn.END, r.readString());

    assertEquals("unpack error Missing commit " + P.name(), r.readString());
    assertEquals("ng refs/heads/s n/a (unpacker error)", r.readString());
    assertSame(PacketLineIn.END, r.readString());
  }
Example #6
0
  private void validateCommands() {
    for (final ReceiveCommand cmd : commands) {
      final Ref ref = cmd.getRef();
      if (cmd.getResult() != Result.NOT_ATTEMPTED) continue;

      if (cmd.getType() == ReceiveCommand.Type.DELETE && !isAllowDeletes()) {
        // Deletes are not supported on this repository.
        //
        cmd.setResult(Result.REJECTED_NODELETE);
        continue;
      }

      if (cmd.getType() == ReceiveCommand.Type.CREATE) {
        if (!isAllowCreates()) {
          cmd.setResult(Result.REJECTED_NOCREATE);
          continue;
        }

        if (ref != null && !isAllowNonFastForwards()) {
          // Creation over an existing ref is certainly not going
          // to be a fast-forward update. We can reject it early.
          //
          cmd.setResult(Result.REJECTED_NONFASTFORWARD);
          continue;
        }

        if (ref != null) {
          // A well behaved client shouldn't have sent us a
          // create command for a ref we advertised to it.
          //
          cmd.setResult(
              Result.REJECTED_OTHER_REASON,
              MessageFormat.format(JGitText.get().refAlreadyExists, ref));
          continue;
        }
      }

      if (cmd.getType() == ReceiveCommand.Type.DELETE
          && ref != null
          && !ObjectId.zeroId().equals(cmd.getOldId())
          && !ref.getObjectId().equals(cmd.getOldId())) {
        // Delete commands can be sent with the old id matching our
        // advertised value, *OR* with the old id being 0{40}. Any
        // other requested old id is invalid.
        //
        cmd.setResult(Result.REJECTED_OTHER_REASON, JGitText.get().invalidOldIdSent);
        continue;
      }

      if (cmd.getType() == ReceiveCommand.Type.UPDATE) {
        if (ref == null) {
          // The ref must have been advertised in order to be updated.
          //
          cmd.setResult(Result.REJECTED_OTHER_REASON, JGitText.get().noSuchRef);
          continue;
        }

        if (!ref.getObjectId().equals(cmd.getOldId())) {
          // A properly functioning client will send the same
          // object id we advertised.
          //
          cmd.setResult(Result.REJECTED_OTHER_REASON, JGitText.get().invalidOldIdSent);
          continue;
        }

        // Is this possibly a non-fast-forward style update?
        //
        RevObject oldObj, newObj;
        try {
          oldObj = walk.parseAny(cmd.getOldId());
        } catch (IOException e) {
          cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd.getOldId().name());
          continue;
        }

        try {
          newObj = walk.parseAny(cmd.getNewId());
        } catch (IOException e) {
          cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd.getNewId().name());
          continue;
        }

        if (oldObj instanceof RevCommit && newObj instanceof RevCommit) {
          try {
            if (!walk.isMergedInto((RevCommit) oldObj, (RevCommit) newObj)) {
              cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
            }
          } catch (MissingObjectException e) {
            cmd.setResult(Result.REJECTED_MISSING_OBJECT, e.getMessage());
          } catch (IOException e) {
            cmd.setResult(Result.REJECTED_OTHER_REASON);
          }
        } else {
          cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
        }
      }

      if (!cmd.getRefName().startsWith(Constants.R_REFS)
          || !Repository.isValidRefName(cmd.getRefName())) {
        cmd.setResult(Result.REJECTED_OTHER_REASON, JGitText.get().funnyRefname);
      }
    }
  }
Example #7
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    handleAuth(req);
    resp.setCharacterEncoding("UTF-8");
    final PrintWriter out = resp.getWriter();
    try {
      String pathInfo = req.getPathInfo();
      Pattern pattern = Pattern.compile("/([^/]*)(?:/([^/]*)(?:/(.*))?)?");
      Matcher matcher = pattern.matcher(pathInfo);
      matcher.matches();
      String projectName = null;
      String refName = null;
      String filePath = null;
      if (matcher.groupCount() > 0) {
        projectName = matcher.group(1);
        refName = matcher.group(2);
        filePath = matcher.group(3);
        if (projectName == null || projectName.equals("")) {
          projectName = null;
        } else {
          projectName = java.net.URLDecoder.decode(projectName, "UTF-8");
        }
        if (refName == null || refName.equals("")) {
          refName = null;
        } else {
          refName = java.net.URLDecoder.decode(refName, "UTF-8");
        }
        if (filePath == null || filePath.equals("")) {
          filePath = null;
        } else {
          filePath = java.net.URLDecoder.decode(filePath, "UTF-8");
        }
      }
      if (projectName != null) {
        if (filePath == null) filePath = "";
        NameKey projName = NameKey.parse(projectName);

        ProjectControl control;
        try {
          control = projControlFactory.controlFor(projName);
          if (!control.isVisible()) {
            log.debug("Project not visible!");
            resp.sendError(
                HttpServletResponse.SC_UNAUTHORIZED,
                "You need to be logged in to see private projects");
            return;
          }
        } catch (NoSuchProjectException e1) {
        }
        Repository repo = repoManager.openRepository(projName);
        if (refName == null) {
          JSONArray contents = new JSONArray();
          List<Ref> call;
          try {
            call = new Git(repo).branchList().call();
            Git git = new Git(repo);
            for (Ref ref : call) {
              JSONObject jsonObject = new JSONObject();
              try {
                jsonObject.put("name", ref.getName());
                jsonObject.put("type", "ref");
                jsonObject.put("size", "0");
                jsonObject.put("path", "");
                jsonObject.put("project", projectName);
                jsonObject.put("ref", ref.getName());
                lastCommit(git, null, ref.getObjectId(), jsonObject);
              } catch (JSONException e) {
              }
              contents.put(jsonObject);
            }
            String response = contents.toString();
            resp.setContentType("application/json");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("ETag", "W/\"" + response.length() + "-" + response.hashCode() + "\"");
            log.debug(response);
            out.write(response);
          } catch (GitAPIException e) {
          }
        } else {
          Ref head = repo.getRef(refName);
          if (head == null) {
            JSONArray contents = new JSONArray();
            String response = contents.toString();
            resp.setContentType("application/json");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("ETag", "W/\"" + response.length() + "-" + response.hashCode() + "\"");
            log.debug(response);
            out.write(response);
            return;
          }
          RevWalk walk = new RevWalk(repo);
          // add try catch to catch failures
          Git git = new Git(repo);
          RevCommit commit = walk.parseCommit(head.getObjectId());
          RevTree tree = commit.getTree();
          TreeWalk treeWalk = new TreeWalk(repo);
          treeWalk.addTree(tree);
          treeWalk.setRecursive(false);
          if (!filePath.equals("")) {
            PathFilter pathFilter = PathFilter.create(filePath);
            treeWalk.setFilter(pathFilter);
          }
          if (!treeWalk.next()) {
            CanonicalTreeParser canonicalTreeParser =
                treeWalk.getTree(0, CanonicalTreeParser.class);
            JSONArray contents = new JSONArray();
            if (canonicalTreeParser != null) {
              while (!canonicalTreeParser.eof()) {
                String path = canonicalTreeParser.getEntryPathString();
                FileMode mode = canonicalTreeParser.getEntryFileMode();
                listEntry(
                    path,
                    mode.equals(FileMode.TREE) ? "dir" : "file",
                    "0",
                    path,
                    projectName,
                    head.getName(),
                    git,
                    contents);
                canonicalTreeParser.next();
              }
            }
            String response = contents.toString();
            resp.setContentType("application/json");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("ETag", "\"" + tree.getId().getName() + "\"");
            log.debug(response);
            out.write(response);
          } else {
            // if (treeWalk.isSubtree()) {
            // treeWalk.enterSubtree();
            // }

            JSONArray contents = getListEntries(treeWalk, repo, git, head, filePath, projectName);
            String response = contents.toString();

            resp.setContentType("application/json");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("ETag", "\"" + tree.getId().getName() + "\"");
            log.debug(response);
            out.write(response);
          }
          walk.release();
          treeWalk.release();
        }
      }
    } catch (RepositoryNotFoundException e) {
      handleException(resp, e, 400);
    } catch (MissingObjectException e) {
      // example "Missing unknown 7035305927ca125757ecd8407e608f6dcf0bd8a5"
      // usually indicative of being unable to locate a commit from a submodule
      log.error(e.getMessage(), e);
      String msg =
          e.getMessage()
              + ".  This exception could have been caused by the use of a git submodule, "
              + "which is currently not supported by the repository browser.";
      handleException(resp, new Exception(msg), 501);
    } catch (IOException e) {
      handleException(resp, e, 500);
    } finally {
      out.close();
    }
  }