List of usage examples for org.eclipse.jgit.transport ReceivePack ReceivePack
public ReceivePack(Repository into)
From source file:com.cisco.step.jenkins.plugins.jenkow.JenkowWorkflowRepository.java
License:Open Source License
ReceivePack createReceivePack(Repository db) {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
ReceivePack rp = new ReceivePack(db);
rp.setPostReceiveHook(new GitPostReceiveHook());
return rp;/*from w ww .ja va 2 s . c om*/
}
From source file:com.google.gerrit.server.git.ReceiveCommits.java
License:Apache License
@Inject ReceiveCommits(final ReviewDb db, final Provider<InternalChangeQuery> queryProvider, final SchemaFactory<ReviewDb> schemaFactory, final ChangeData.Factory changeDataFactory, final ChangeUpdate.Factory updateFactory, final AccountResolver accountResolver, final CmdLineParser.Factory optionParserFactory, final MergedSender.Factory mergedSenderFactory, final ReplacePatchSetSender.Factory replacePatchSetFactory, final GitReferenceUpdated gitRefUpdated, final PatchSetInfoFactory patchSetInfoFactory, final ChangeHooks hooks, final ApprovalsUtil approvalsUtil, final ApprovalCopier approvalCopier, final ChangeMessagesUtil cmUtil, final ProjectCache projectCache, final GitRepositoryManager repoManager, final TagCache tagCache, final AccountCache accountCache, final ChangeCache changeCache, final ChangesCollection changes, final ChangeInserter.Factory changeInserterFactory, final CommitValidators.Factory commitValidatorsFactory, @CanonicalWebUrl final String canonicalWebUrl, final WorkQueue workQueue, @ChangeUpdateExecutor ListeningExecutorService changeUpdateExector, final RequestScopePropagator requestScopePropagator, final ChangeIndexer indexer, final SshInfo sshInfo, final AllProjectsName allProjectsName, ReceiveConfig config, @Assisted final ProjectControl projectControl, @Assisted final Repository repo, final Provider<SubmoduleOp> subOpProvider, final Provider<Submit> submitProvider, final Provider<MergeOp> mergeOpProvider, final ChangeKindCache changeKindCache, final DynamicMap<ProjectConfigEntry> pluginConfigEntries, final NotesMigration notesMigration, final ChangeEditUtil editUtil) throws IOException { this.currentUser = (IdentifiedUser) projectControl.getCurrentUser(); this.db = db; this.queryProvider = queryProvider; this.changeDataFactory = changeDataFactory; this.updateFactory = updateFactory; this.schemaFactory = schemaFactory; this.accountResolver = accountResolver; this.optionParserFactory = optionParserFactory; this.mergedSenderFactory = mergedSenderFactory; this.replacePatchSetFactory = replacePatchSetFactory; this.gitRefUpdated = gitRefUpdated; this.patchSetInfoFactory = patchSetInfoFactory; this.hooks = hooks; this.approvalsUtil = approvalsUtil; this.approvalCopier = approvalCopier; this.cmUtil = cmUtil; this.projectCache = projectCache; this.repoManager = repoManager; this.canonicalWebUrl = canonicalWebUrl; this.tagCache = tagCache; this.accountCache = accountCache; this.changes = changes; this.changeInserterFactory = changeInserterFactory; this.commitValidatorsFactory = commitValidatorsFactory; this.workQueue = workQueue; this.changeUpdateExector = changeUpdateExector; this.requestScopePropagator = requestScopePropagator; this.indexer = indexer; this.sshInfo = sshInfo; this.allProjectsName = allProjectsName; this.receiveConfig = config; this.changeKindCache = changeKindCache; this.projectControl = projectControl; this.labelTypes = projectControl.getLabelTypes(); this.project = projectControl.getProject(); this.repo = repo; this.rp = new ReceivePack(repo); this.rejectCommits = BanCommit.loadRejectCommitsMap(repo, rp.getRevWalk()); this.subOpProvider = subOpProvider; this.submitProvider = submitProvider; this.mergeOpProvider = mergeOpProvider; this.pluginConfigEntries = pluginConfigEntries; this.notesMigration = notesMigration; this.editUtil = editUtil; this.messageSender = new ReceivePackMessageSender(); ProjectState ps = projectControl.getProjectState(); this.newChangeForAllNotInTarget = ps.isCreateNewChangeForAllNotInTarget(); rp.setAllowCreates(true);//from w w w . j av a 2 s. c o m rp.setAllowDeletes(true); rp.setAllowNonFastForwards(true); rp.setCheckReceivedObjects(ps.getConfig().getCheckReceivedObjects()); rp.setRefFilter(new RefFilter() { @Override public Map<String, Ref> filter(Map<String, Ref> refs) { Map<String, Ref> filteredRefs = Maps.newHashMapWithExpectedSize(refs.size()); for (Map.Entry<String, Ref> e : refs.entrySet()) { String name = e.getKey(); if (!name.startsWith(REFS_CHANGES) && !name.startsWith(RefNames.REFS_CACHE_AUTOMERGE)) { filteredRefs.put(name, e.getValue()); } } return filteredRefs; } }); if (!projectControl.allRefsAreVisible()) { rp.setCheckReferencedObjectsAreReachable(config.checkReferencedObjectsAreReachable); rp.setAdvertiseRefsHook(new VisibleRefFilter(tagCache, changeCache, repo, projectControl, db, false)); } List<AdvertiseRefsHook> advHooks = new ArrayList<>(3); advHooks.add(new AdvertiseRefsHook() { @Override public void advertiseRefs(BaseReceivePack rp) throws ServiceMayNotContinueException { allRefs = rp.getAdvertisedRefs(); if (allRefs == null) { try { allRefs = rp.getRepository().getRefDatabase().getRefs(ALL); } catch (ServiceMayNotContinueException e) { throw e; } catch (IOException e) { ServiceMayNotContinueException ex = new ServiceMayNotContinueException(); ex.initCause(e); throw ex; } } rp.setAdvertisedRefs(allRefs, rp.getAdvertisedObjects()); } @Override public void advertiseRefs(UploadPack uploadPack) { } }); advHooks.add(rp.getAdvertiseRefsHook()); advHooks.add( new ReceiveCommitsAdvertiseRefsHook(db, queryProvider, projectControl.getProject().getNameKey())); rp.setAdvertiseRefsHook(AdvertiseRefsHookChain.newChain(advHooks)); }
From source file:com.sonatype.sshjgit.core.gitcommand.Receive.java
License:Apache License
@Override protected void runImpl() throws IOException, Failure { final Subject subject = SecurityUtils.getSubject(); subject.checkPermission("gitrepo:push:" + getRepoNameAsPermissionParts(repo)); ReceivePack rp = new ReceivePack(repo); rp.setAllowCreates(true);//from w w w.j ava 2 s. c o m final boolean mayNonFastForward = subject .isPermitted("gitrepo:non-fast-forward:" + getRepoNameAsPermissionParts(repo)); rp.setAllowDeletes(mayNonFastForward); rp.setAllowNonFastForwards(mayNonFastForward); rp.setCheckReceivedObjects(true); // TODO make this be a real email address! final String name; final Object principal = subject.getPrincipal(); if (principal == null) { name = "null_principal"; log.warn("principal was null when trying to setRefLogIdent on repo."); } else { name = principal.toString(); } log.info("setting LogIdent to " + name); rp.setRefLogIdent(new PersonIdent(name, name + "@example.com")); rp.receive(in, out, err); }
From source file:com.tasktop.c2c.server.scm.web.GitHandler.java
License:Open Source License
@Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final boolean containerSupportsChunkedIO = computeContainerSupportsChunkedIO(); String pathInfo = request.getPathInfo(); log.info("Git request: " + request.getMethod() + " " + request.getRequestURI() + " " + pathInfo); Repository repository = null;/*from w w w.j a va 2s.co m*/ try { // only work on Git requests Matcher matcher = pathInfo == null ? null : GIT_COMMAND_PATTERN.matcher(pathInfo); if (matcher == null || !matcher.matches()) { log.info("Unexpected path: " + pathInfo); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String requestCommand = matcher.group(1); String requestPath = matcher.group(2); // sanity check on path, disallow path separator components if (requestPath == null || requestPath.contains("/") || requestPath.contains("..")) { badPathResponse(); } repository = repositoryResolver.open(request, requestPath); InputStream requestInput = request.getInputStream(); if (!containerSupportsChunkedIO) { requestInput = new ChunkedInputStream(requestInput); } MultiplexingOutputStream mox = createMultiplexingOutputStream(response, containerSupportsChunkedIO); // indicate that we're ok to handle the request // note that following this there will be a two-way communication with the process // that might still encounter errors. That's ok. startOkResponse(response, containerSupportsChunkedIO); // identify the git command GitCommand command = GitCommand.fromCommandName(requestCommand); if (command != null) { // permissions check if (!Security.hasOneOfRoles(command.getRoles())) { log.info("Access denied to " + Security.getCurrentUser() + " for " + command.getCommandName() + " on " + TenancyUtil.getCurrentTenantProjectIdentifer() + " " + requestPath); response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } switch (command) { case RECEIVE_PACK: ReceivePack rp = new ReceivePack(repository); rp.setPostReceiveHook(postReceiveHook); rp.receive(requestInput, mox.stream(PacketType.STDOUT), mox.stream(PacketType.STDERR)); break; case UPLOAD_PACK: UploadPack up = new UploadPack(repository); up.upload(requestInput, mox.stream(PacketType.STDOUT), mox.stream(PacketType.STDERR)); break; default: response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } // at this stage we're done with IO // send the exit value and closing chunk try { int exitValue = 0; if (exitValue != 0) { log.info("Exit value: " + exitValue); } mox.writeExitCode(exitValue); mox.close(); } catch (IOException e) { // ignore log.debug("Cannot complete writing exit state", e); } // clear interrupt status Thread.interrupted(); } catch (ErrorResponseException e) { createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage()); } catch (ServiceNotAuthorizedException e) { createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage()); } catch (ServiceNotEnabledException e) { createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage()); } finally { log.info("Git request complete"); if (repository != null) { repository.close(); } } }
From source file:net.antoniy.gidder.beta.ssh.Receive.java
License:Apache License
@Override protected void runImpl() throws IOException { if (!hasPermission()) { err.write(MSG_REPOSITORY_PERMISSIONS.getBytes()); err.flush();/*from w ww.j a va 2 s. c om*/ onExit(CODE_ERROR, MSG_REPOSITORY_PERMISSIONS); return; } // Config config = new Config(); // int timeout = Integer.parseInt(config.getString("transfer", null, "timeout")); int timeout = 10; // PackConfig packConfig = new PackConfig(); // packConfig.setDeltaCompress(false); // packConfig.setThreads(1); // packConfig.fromConfig(config); final ReceivePack rp = new ReceivePack(repo); rp.setTimeout(timeout); rp.receive(in, out, err); }
From source file:net.community.chest.gitcloud.facade.backend.git.BackendReceivePackFactory.java
License:Apache License
@Override public ReceivePack create(C request, Repository db) throws ServiceNotEnabledException, ServiceNotAuthorizedException { final String logPrefix; if (request instanceof HttpServletRequest) { HttpServletRequest req = (HttpServletRequest) request; logPrefix = "create(" + req.getMethod() + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]"; } else {//from w w w.jav a 2 s .co m logPrefix = "create(" + db.getDirectory() + ")"; } if (logger.isDebugEnabled()) { logger.debug(logPrefix + ": " + db.getDirectory()); } ReceivePack receive = new ReceivePack(db) { @Override @SuppressWarnings("synthetic-access") public void receive(InputStream input, OutputStream output, OutputStream messages) throws IOException { InputStream effIn = input; OutputStream effOut = output, effMessages = messages; if (logger.isTraceEnabled()) { LineLevelAppender inputAppender = new LineLevelAppender() { @Override public void writeLineData(CharSequence lineData) throws IOException { logger.trace(logPrefix + " upload(C): " + lineData); } @Override public boolean isWriteEnabled() { return true; } }; effIn = new TeeInputStream(effIn, new HexDumpOutputStream(inputAppender), true); LineLevelAppender outputAppender = new LineLevelAppender() { @Override public void writeLineData(CharSequence lineData) throws IOException { logger.trace(logPrefix + " upload(S): " + lineData); } @Override public boolean isWriteEnabled() { return true; } }; effOut = new TeeOutputStream(effOut, new HexDumpOutputStream(outputAppender)); if (effMessages != null) { LineLevelAppender messagesAppender = new LineLevelAppender() { @Override public void writeLineData(CharSequence lineData) throws IOException { logger.trace(logPrefix + " upload(M): " + lineData); } @Override public boolean isWriteEnabled() { return true; } }; // TODO review the decision to use an AsciiLineOutputStream here effMessages = new TeeOutputStream(effMessages, new AsciiLineOutputStream(messagesAppender)); } } super.receive(effIn, effOut, effMessages); } }; receive.setTimeout(receiveTimeoutValue); // TODO set pushing user identity for reflog // receive.setRefLogIdent(new PersonIdent(user.username, user.username + "@" + origin)) // TODO set advanced options // receive.setAllowCreates(user.canCreateRef(repository)); // receive.setAllowDeletes(user.canDeleteRef(repository)); // receive.setAllowNonFastForwards(user.canRewindRef(repository)); // TODO setup the receive hooks // receive.setPreReceiveHook(preRcvHook); // receive.setPostReceiveHook(postRcvHook); return receive; }
From source file:org.apache.sshd.git.pack.GitPackCommand.java
License:Apache License
@Override public void run() { try {/* w w w .j av a 2 s. co m*/ List<String> strs = parseDelimitedString(command, " ", true); String[] args = strs.toArray(new String[strs.size()]); for (int i = 0; i < args.length; i++) { if (args[i].startsWith("'") && args[i].endsWith("'")) { args[i] = args[i].substring(1, args[i].length() - 1); } if (args[i].startsWith("\"") && args[i].endsWith("\"")) { args[i] = args[i].substring(1, args[i].length() - 1); } } if (args.length != 2) { throw new IllegalArgumentException("Invalid git command line: " + command); } File srcGitdir = new File(rootDir, args[1]); RepositoryCache.FileKey key = RepositoryCache.FileKey.lenient(srcGitdir, FS.DETECTED); Repository db = key.open(true /* must exist */); if ("git-upload-pack".equals(args[0])) { new UploadPack(db).upload(in, out, err); } else if ("git-receive-pack".equals(args[0])) { new ReceivePack(db).receive(in, out, err); } else { throw new IllegalArgumentException("Unknown git command: " + command); } } catch (Throwable t) { t.printStackTrace(); } if (callback != null) { callback.onExit(0); } }
From source file:org.kercoin.magrit.sshd.commands.ReceivePackCommand.java
License:Open Source License
public ReceivePackCommand command(String command) throws IOException { this.receivePack = new ReceivePack(parse(command)); this.receivePack.setBiDirectionalPipe(true); this.receivePack.setTimeout(5); return this; }
From source file:org.kie.commons.java.nio.fs.jgit.JGitFileSystemProvider.java
License:Apache License
private void buildAndStartDeamon() { deamonService = new Daemon(new InetSocketAddress(DEAMON_HOST, DEAMON_PORT)); deamonService.getService("git-receive-pack").setEnabled(DEAMON_UPLOAD); deamonService.setRepositoryResolver(new RepositoryResolverImpl()); deamonService.setReceivePackFactory(new ReceivePackFactory<DaemonClient>() { @Override/* www . ja v a 2 s. c o m*/ public ReceivePack create(final DaemonClient req, final Repository db) throws ServiceNotEnabledException, ServiceNotAuthorizedException { return new ReceivePack(db) { { final ClusterService clusterService = clusterMap.get(db); final JGitFileSystem fs = repoIndex.get(db); final String treeRef = "master"; final ObjectId oldHead = JGitUtil.getTreeRefObjectId(db, treeRef); setPreReceiveHook(new PreReceiveHook() { @Override public void onPreReceive(final ReceivePack rp, final Collection<ReceiveCommand> commands) { if (clusterService != null) { clusterService.lock(); } } }); setPostReceiveHook(new PostReceiveHook() { @Override public void onPostReceive(final ReceivePack rp, final Collection<ReceiveCommand> commands) { final ObjectId newHead = JGitUtil.getTreeRefObjectId(db, treeRef); notifyDiffs(fs, treeRef, oldHead, newHead); if (clusterService != null) { clusterService.broadcast(new MessageType() { @Override public String toString() { return "SYNC_FS"; } @Override public int hashCode() { return "SYNC_FS".hashCode(); } }, new HashMap<String, String>() { { put("fs_scheme", "git"); put("fs_id", fs.id()); put("fs_uri", fs.toString()); } }); clusterService.unlock(); } } }); } }; } }); try { deamonService.start(); } catch (java.io.IOException e) { throw new IOException(e); } }
From source file:org.uberfire.java.nio.fs.jgit.JGitFileSystemProvider.java
License:Apache License
private void buildAndStartSSH() { final ReceivePackFactory receivePackFactory = new ReceivePackFactory<BaseGitCommand>() { @Override/*from w ww.j ava2s .co m*/ public ReceivePack create(final BaseGitCommand req, final Repository db) throws ServiceNotEnabledException, ServiceNotAuthorizedException { return new ReceivePack(db) { { final ClusterService clusterService = clusterMap.get(db); final JGitFileSystem fs = repoIndex.get(db); final Map<String, ObjectId> oldTreeRefs = new HashMap<String, ObjectId>(); setPreReceiveHook(new PreReceiveHook() { @Override public void onPreReceive(final ReceivePack rp, final Collection<ReceiveCommand> commands) { if (clusterService != null) { clusterService.lock(); } for (final ReceiveCommand command : commands) { oldTreeRefs.put(command.getRefName(), JGitUtil.getTreeRefObjectId(db, command.getRefName())); } } }); setPostReceiveHook(new PostReceiveHook() { @Override public void onPostReceive(final ReceivePack rp, final Collection<ReceiveCommand> commands) { for (Map.Entry<String, ObjectId> oldTreeRef : oldTreeRefs.entrySet()) { notifyDiffs(fs, oldTreeRef.getKey(), "<ssh>", req.getUser().getName(), oldTreeRef.getValue(), JGitUtil.getTreeRefObjectId(db, oldTreeRef.getKey())); } if (clusterService != null) { //TODO {porcelli} hack, that should be addressed in future clusterService.broadcast(DEFAULT_IO_SERVICE_NAME, new MessageType() { @Override public String toString() { return "SYNC_FS"; } @Override public int hashCode() { return "SYNC_FS".hashCode(); } }, new HashMap<String, String>() { { put("fs_scheme", "git"); put("fs_id", fs.id()); put("fs_uri", fs.toString()); } }); clusterService.unlock(); } } }); } }; } }; gitSSHService = new GitSSHService(); gitSSHService.setup(SSH_FILE_CERT_DIR, SSH_HOST_ADDR, SSH_PORT, authenticationManager, authorizationManager, receivePackFactory, new RepositoryResolverImpl<BaseGitCommand>()); gitSSHService.start(); }