List of usage examples for org.eclipse.jgit.lib Repository getDirectory
public File getDirectory()
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 {/*w w w . j a v a2s . c o 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:net.community.chest.gitcloud.facade.backend.git.BackendRepositoryResolverTest.java
License:Apache License
@Test public void testOpenExistingRepository() throws Exception { final String REPO_NAME = "testOpenExistingRepository"; File expected = new File(reposDir, REPO_NAME + Constants.DOT_GIT_EXT); if (!expected.exists()) { Repository repo = new FileRepository(expected); try {/* ww w . j ava2 s . c om*/ repo.create(true); } finally { repo.close(); } } else { assertTrue("Test repo not a folder: " + expected, expected.isDirectory()); } for (String ext : TEST_EXTS) { Repository repo = resolver.open(null, REPO_NAME + ext); assertNotNull("No resolution result for ext=" + ext, repo); try { File actual = repo.getDirectory(); assertEquals("Mismatched resolved location for ext=" + ext, expected, actual); } finally { repo.close(); } } }
From source file:net.community.chest.gitcloud.facade.backend.git.BackendRepositoryResolverTest.java
License:Apache License
@Test public void testOpenNonExistingRepository() throws Exception { final String REPO_NAME = "testOpenNonExistingRepository"; File gitDir = new File(reposDir, REPO_NAME + Constants.DOT_GIT_EXT); FileUtils.deleteDirectory(gitDir);/*ww w . ja v a 2 s . c o m*/ assertFalse("Failed to delete " + gitDir, gitDir.exists()); for (String ext : TEST_EXTS) { try { Repository repo = resolver.open(null, REPO_NAME + ext); try { fail("Unexpected success for ext=" + ext + ": " + repo.getDirectory()); } finally { repo.close(); } } catch (RepositoryNotFoundException e) { // expected - ignored } } }
From source file:net.community.chest.gitcloud.facade.backend.git.BackendRepositoryResolverTest.java
License:Apache License
@Test public void testDeepDownRepositoryResolution() throws Exception { final String REPO_NAME = "testDeepDownRepositoryResolution", GIT_NAME = REPO_NAME + Constants.DOT_GIT_EXT; final int MAX_DEPTH = Byte.SIZE; StringBuilder sb = new StringBuilder(MAX_DEPTH + Long.SIZE); File parentDir = reposDir;/*ww w.j a v a2s . c o m*/ for (int depth = 0; depth < MAX_DEPTH; depth++) { String subName = String.valueOf(depth); parentDir = new File(parentDir, subName); sb.append(subName).append('/'); File gitDir = new File(parentDir, GIT_NAME); if (!gitDir.exists()) { Repository repo = new FileRepository(gitDir); try { repo.create(true); } finally { repo.close(); } } else { assertTrue("Child repo not a folder: " + gitDir, gitDir.isDirectory()); } int curLen = sb.length(); try { sb.append(REPO_NAME); int baseLen = sb.length(); for (String ext : TEST_EXTS) { try { Repository repo = resolver.open(null, sb.append(ext).toString()); assertNotNull("No resolution result for ext=" + ext, repo); try { File actual = repo.getDirectory(); assertEquals("Mismatched resolved location for ext=" + ext, gitDir, actual); } finally { repo.close(); } } finally { sb.setLength(baseLen); } } } finally { sb.setLength(curLen); } } }
From source file:net.community.chest.gitcloud.facade.backend.git.BackendUploadPackFactory.java
License:Apache License
@Override public UploadPack create(final C request, Repository db) throws ServiceNotEnabledException, ServiceNotAuthorizedException { final File dir = db.getDirectory(); final String logPrefix; if (request instanceof HttpServletRequest) { HttpServletRequest req = (HttpServletRequest) request; logPrefix = "create(" + req.getMethod() + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]"; } else {//from w w w . j a v a2s .c o m logPrefix = "create(" + dir.getAbsolutePath() + ")"; } if (logger.isDebugEnabled()) { logger.debug(logPrefix + ": " + dir.getAbsolutePath()); } UploadPack up = new UploadPack(db) { @Override @SuppressWarnings("synthetic-access") public void upload(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.upload(effIn, effOut, effMessages); } @Override @SuppressWarnings("synthetic-access") public void sendAdvertisedRefs(RefAdvertiser adv) throws IOException, ServiceMayNotContinueException { RefAdvertiser effAdv = adv; if (logger.isTraceEnabled() && (adv instanceof PacketLineOutRefAdvertiser)) { PacketLineOut pckOut = (PacketLineOut) ReflectionUtils.getField(pckOutField, adv); effAdv = new PacketLineOutRefAdvertiser(pckOut) { private final PacketLineOut pckLog = new PacketLineOut( // TODO review the decision to use an AsciiLineOutputStream here new AsciiLineOutputStream(new LineLevelAppender() { @Override public void writeLineData(CharSequence lineData) throws IOException { logger.trace(logPrefix + " S: " + lineData); } @Override public boolean isWriteEnabled() { return true; } })); @Override protected void writeOne(CharSequence line) throws IOException { String s = line.toString(); super.writeOne(s); pckLog.writeString(s); } @Override protected void end() throws IOException { super.end(); pckLog.end(); } }; } super.sendAdvertisedRefs(effAdv); } }; up.setTimeout(uploadTimeoutValue); return up; }
From source file:net.erdfelt.android.sdkfido.git.internal.GitInfo.java
License:Apache License
public static void infoAll(Repository db) throws IOException { System.out.printf("Repository - %s%n", db.getDirectory()); System.out.printf(" state: %s%n", db.getRepositoryState()); System.out.printf(" branch: %s%n", db.getBranch()); System.out.printf("full-branch: %s%n", db.getFullBranch()); infoRefs(db);//from w w w . j a v a 2 s . co m infoBranches(db); infoTags(db); }
From source file:net.morimekta.idltool.IdlUtils.java
License:Apache License
public static Meta getMetaInRegistry(Repository repo) throws IOException, GitAPIException { // use tree and meta.json file to show available services. ObjectId lastCommitId = repo.resolve(Constants.HEAD); // now we have to get the commit RevWalk revWalk = new RevWalk(repo); RevCommit commit = revWalk.parseCommit(lastCommitId); // and using commit's tree find the path RevTree tree = commit.getTree();//from www .ja va2s . c o m TreeWalk treeWalk = new TreeWalk(repo); treeWalk.addTree(tree); treeWalk.setRecursive(true); treeWalk.setFilter(PathFilter.create(Idl_Constants.META_JSON)); if (!treeWalk.next()) { throw new RuntimeException("No registry meta file found, should be at " + new File(repo.getDirectory(), Idl_Constants.META_JSON).getCanonicalFile().getAbsolutePath()); } ObjectId objectId = treeWalk.getObjectId(0); ObjectLoader loader = repo.open(objectId); // and then one can use either InputStream in = loader.openStream(); return new JsonSerializer().deserialize(in, Meta.kDescriptor); }
From source file:net.polydawn.mdm.Plumbing.java
License:Open Source License
public static boolean fetch(Repository repo, MdmModuleDependency module) throws ConfigInvalidException, MdmRepositoryIOException, MdmRepositoryStateException, MdmException, IOException { switch (module.getStatus().getType()) { case MISSING: throw new MajorBug(); case UNINITIALIZED: if (module.getRepo() == null) try { RepositoryBuilder builder = new RepositoryBuilder(); builder.setWorkTree(new File(repo.getWorkTree() + "/" + module.getPath())); builder.setGitDir(new File(repo.getDirectory() + "/modules/" + module.getPath())); module.repo = builder.build(); // we actually *might* not have to make the repo from zero. // this getRepo gets its effective data from SubmoduleWalk.getSubmoduleRepository... // which does its job by looking in the working tree of the parent repo. // meaning if it finds nothing, it certainly won't find any gitdir indirections. // so, even if this is null, we might well have a gitdir cached that we still have to go find. final FileBasedConfig cfg = (FileBasedConfig) module.repo.getConfig(); if (!cfg.getFile().exists()) { // though seemly messy, this is the same question the jgit create() function asks, and it's not exposed to us, so. module.repo.create(false); } else { // do something crazy, because... i think the user's expectation after blowing away their submodule working tree is likely wanting a clean state of index and such here try { new Git(module.getRepo()).reset().setMode(ResetType.HARD).call(); } catch (CheckoutConflictException e) { /* Can a hard reset even have a conflict? */ throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); }/* ww w . j a va 2 s . co m*/ } // set up a working tree which points to the gitdir in the parent repo: // handling paths in java, god forbid relative paths, is such an unbelievable backwater. someday please make a whole library that actually disambiguates pathnames from filedescriptors properly int ups = StringUtils.countMatches(module.getPath(), "/"); // look up the path between the `repo` and its possible git dir location. if the gitdir is relocated, we have adjust our own relocations to compensate. String parentGitPointerStr = ".git/"; String parentWorktreePointerStr = "../"; // load it ourselves because we explicitly want the unresolved path, not what jgit would give us back from `repo.getDirectory().toString()`. File parentGitPointer = new File(repo.getWorkTree(), ".git"); if (parentGitPointer.isFile()) { // this shouldn't have to be recursive fortunately (that recursion is done implicitly by the chaining of each guy at each stage). // this does however feel fairly fragile. it's considerable that perhaps we should try to heuristically determine when paths are just to crazy to deal with. but, on the off chance that check was overzealous, it would be very irritating, so let's not. // frankly, if you're doing deeply nested submodules, or other advanced gitdir relocations, at some point you're taking it upon yourself to deal with the inevitably complex outcomes and edge case limitations. parentGitPointerStr = IOForge.readFileAsString(parentGitPointer); if (!"gitdir:".equals(parentGitPointerStr.substring(0, 7))) throw new ConfigInvalidException( "cannot understand location of parent project git directory"); parentGitPointerStr = parentGitPointerStr.substring(7).trim() + "/"; parentWorktreePointerStr = repo.getConfig().getString("core", null, "worktree") + "/"; } // jgit does not appear to create the .git file correctly here :/ // nor even consider it to be jgit's job to create the worktree yet, apparently, so do that module.repo.getWorkTree().mkdirs(); // need modules/[module]/config to contain 'core.worktree' = appropriate String submoduleWorkTreeRelativeToGitDir = StringUtils.repeat("../", ups + 2) + parentWorktreePointerStr + module.getPath(); StoredConfig cnf = module.repo.getConfig(); cnf.setString("core", null, "worktree", submoduleWorkTreeRelativeToGitDir); cnf.save(); // need [module]/.git to contain 'gitdir: appropriate' (which appears to not be normal gitconfig) String submoduleGitDirRelativeToWorkTree = StringUtils.repeat("../", ups + 1) + parentGitPointerStr + "modules/" + module.getPath(); IOForge.saveFile("gitdir: " + submoduleGitDirRelativeToWorkTree + "\n", new File(module.repo.getWorkTree(), ".git")); } catch (IOException e) { throw new MdmRepositoryIOException("create a new submodule", true, module.getHandle(), e); } try { if (initLocalConfig(repo, module)) repo.getConfig().save(); } catch (IOException e) { throw new MdmRepositoryIOException("save changes", true, "the local git configuration file", e); } try { setMdmRemote(module); module.getRepo().getConfig().save(); } catch (IOException e) { throw new MdmRepositoryIOException("save changes", true, "the git configuration file for submodule " + module.getHandle(), e); } case INITIALIZED: if (module.getVersionName() == null || module.getVersionName().equals(module.getVersionActual())) return false; case REV_CHECKED_OUT: try { if (initModuleConfig(repo, module)) module.getRepo().getConfig().save(); } catch (IOException e) { throw new MdmRepositoryIOException("save changes", true, "the git configuration file for submodule " + module.getHandle(), e); } final String versionBranchName = "refs/heads/mdm/release/" + module.getVersionName(); final String versionTagName = "refs/tags/release/" + module.getVersionName(); /* Fetch only the branch labelled with the version requested. */ if (module.getRepo().getRef(versionBranchName) == null) try { RefSpec releaseBranchRef = new RefSpec().setForceUpdate(true).setSource(versionBranchName) .setDestination(versionBranchName); RefSpec releaseTagRef = new RefSpec().setForceUpdate(true).setSource(versionTagName) .setDestination(versionTagName); new Git(module.getRepo()).fetch().setRemote("origin") .setRefSpecs(releaseBranchRef, releaseTagRef).setTagOpt(TagOpt.NO_TAGS).call(); } catch (InvalidRemoteException e) { throw new MdmRepositoryStateException( "find a valid remote origin in the config for the submodule", module.getHandle(), e); } catch (TransportException e) { URIish remote = null; try { //XXX: if we went through all the work to resolve the remote like the fetch command does, we could just as well do it and hand the resolved uri to fetch for better consistency. remote = new RemoteConfig(module.getRepo().getConfig(), "origin").getURIs().get(0); } catch (URISyntaxException e1) { } throw new MdmRepositoryIOException("fetch from a remote", false, remote.toASCIIString(), e) .setAdditionalMessage("check your connectivity and try again?"); } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } /* Drop the files into the working tree. */ try { new Git(module.getRepo()).checkout().setName(versionBranchName).setForce(true).call(); } catch (RefAlreadyExistsException e) { /* I'm not creating a new branch, so this exception wouldn't even make sense. */ throw new MajorBug(e); } catch (RefNotFoundException e) { /* I just got this branch, so we shouldn't have a problem here. */ throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (InvalidRefNameException e) { /* I just got this branch, so we shouldn't have a problem here. */ throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (CheckoutConflictException e) { // this one is just a perfectly reasonable message with a list of files in conflict; we'll take it. throw new MdmRepositoryStateException(module.getHandle(), e); // this currently gets translated to a :'( exception and it's probably more like a :( } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } return true; default: throw new MajorBug(); } }
From source file:net.polydawn.mdm.Plumbing.java
License:Open Source License
/** * Copy in `url` git config keys from the parent repo config into the submodule config. * This allows for easily having per-project 'insteadof' url rewrites which apply even * when mdm is doing the creation of new repos (which is otherwise a tad hard to get at with git submodules). * @return true if module.getRepo().getConfig() has been modified and should be saved. * @throws ConfigInvalidException/*from w ww.ja v a 2 s. co m*/ * @throws IOException */ public static boolean initModuleConfig(Repository repo, MdmModule module) throws IOException, ConfigInvalidException { Config moduleConfig = module.getRepo().getConfig(); // have to explicitly load the parent repo config in isolate, because `repo.getConfig` includes views of the system and user gitconfig, which we won't want to proxy here. FileBasedConfig parentConfig = new FileBasedConfig(new File(repo.getDirectory(), "config"), repo.getFS()); try { parentConfig.load(); } catch (IOException e) { throw new MdmRepositoryIOException(false, "the local git configuration file", e); } // copy any url_insteadof patterns from the parent repo's git config into the module's git config. // note that we do not strip out any additional insteadof's the module may have; if you've added those, it's none of our business (though at this point, we do overwrite). // see org.eclipse.jgit.transport.RemoteConfig for how these actually get used. for (String url : parentConfig.getSubsections(ConfigConstants.CONFIG_KEY_URL)) for (String insteadOf : parentConfig.getStringList(ConfigConstants.CONFIG_KEY_URL, url, "insteadof")) moduleConfig.setString(ConfigConstants.CONFIG_KEY_URL, url, "insteadof", insteadOf); for (String url : parentConfig.getSubsections(ConfigConstants.CONFIG_KEY_URL)) for (String insteadOf : parentConfig.getStringList(ConfigConstants.CONFIG_KEY_URL, url, "pushinsteadof")) moduleConfig.setString(ConfigConstants.CONFIG_KEY_URL, url, "pushinsteadof", insteadOf); return true; }
From source file:org.apache.gobblin.service.modules.flow.MultiHopFlowCompilerTest.java
License:Apache License
@Test(dependsOnMethods = "testMulticastPath") public void testGitFlowGraphMonitorService() throws IOException, GitAPIException, URISyntaxException, InterruptedException { File remoteDir = new File(TESTDIR + "/remote"); File cloneDir = new File(TESTDIR + "/clone"); File flowGraphDir = new File(cloneDir, "/gobblin-flowgraph"); //Clean up/* www.j a v a 2s . c o m*/ cleanUpDir(TESTDIR); // Create a bare repository RepositoryCache.FileKey fileKey = RepositoryCache.FileKey.exact(remoteDir, FS.DETECTED); Repository remoteRepo = fileKey.open(false); remoteRepo.create(true); Git gitForPush = Git.cloneRepository().setURI(remoteRepo.getDirectory().getAbsolutePath()) .setDirectory(cloneDir).call(); // push an empty commit as a base for detecting changes gitForPush.commit().setMessage("First commit").call(); RefSpec masterRefSpec = new RefSpec("master"); gitForPush.push().setRemote("origin").setRefSpecs(masterRefSpec).call(); URI flowTemplateCatalogUri = this.getClass().getClassLoader().getResource("template_catalog").toURI(); Config config = ConfigBuilder.create() .addPrimitive( GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_REPO_URI, remoteRepo.getDirectory().getAbsolutePath()) .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_REPO_DIR, TESTDIR + "/git-flowgraph") .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_POLLING_INTERVAL, 5) .addPrimitive(ServiceConfigKeys.TEMPLATE_CATALOGS_FULLY_QUALIFIED_PATH_KEY, flowTemplateCatalogUri.toString()) .build(); //Create a MultiHopFlowCompiler instance specCompiler = new MultiHopFlowCompiler(config, Optional.absent(), false); specCompiler.setActive(true); //Ensure node1 is not present in the graph Assert.assertNull(specCompiler.getFlowGraph().getNode("node1")); // push a new node file File nodeDir = new File(flowGraphDir, "node1"); File nodeFile = new File(nodeDir, "node1.properties"); nodeDir.mkdirs(); nodeFile.createNewFile(); Files.write(FlowGraphConfigurationKeys.DATA_NODE_IS_ACTIVE_KEY + "=true\nparam1=val1" + "\n", nodeFile, Charsets.UTF_8); // add, commit, push node gitForPush.add().addFilepattern(formNodeFilePath(flowGraphDir, nodeDir.getName(), nodeFile.getName())) .call(); gitForPush.commit().setMessage("Node commit").call(); gitForPush.push().setRemote("origin").setRefSpecs(masterRefSpec).call(); // polling is every 5 seconds, so wait twice as long and check TimeUnit.SECONDS.sleep(10); //Test that a DataNode is added to FlowGraph DataNode dataNode = specCompiler.getFlowGraph().getNode("node1"); Assert.assertEquals(dataNode.getId(), "node1"); Assert.assertEquals(dataNode.getRawConfig().getString("param1"), "val1"); }