/** * 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)); }
/** * Gets the UserConfig from the given repository. The UserConfig of a repo holds the default * author and committer. * * @param repository the repository * @return the user configuration * @throws CoreException * @see PersonIdent(Repository) * @see CommittHelper#calculateCommitInfo */ private static UserConfig getUserConfig(Repository repository) throws CoreException { Assert.isLegal(repository != null, "Could not get user configuration. No repository provided."); if (repository.getConfig() == null) { throw new CoreException( createStatus( null, "no user configuration (author, committer) are present in repository \"{0}\"", repository.toString())); } return repository.getConfig().get(UserConfig.KEY); }
public void addRemote(Repository toConfigure, String name, Repository remoteRepo) throws IOException { final String refSpec = String.format(REF_SPEC_PATTERN, name); File dest = remoteRepo.getDirectory(); if (!remoteRepo.isBare()) { dest = dest.getParentFile(); } toConfigure.getConfig().setString("remote", name, "fetch", refSpec); toConfigure.getConfig().setString("remote", name, "url", dest.getAbsolutePath()); // write down configuration in .git/config toConfigure.getConfig().save(); }
/** * 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; }
/** * 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()); }
@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); }
@Test public void testCreate_Enabled() throws ServiceNotEnabledException, ServiceNotAuthorizedException { db.getConfig().setBoolean("http", null, "getanyfile", true); service.access(new R(null, "1.2.3.4"), db); service.access(new R("bob", "1.2.3.4"), db); }
/** * Adds the given uri of a remote repository to the given repository by the given name. * * @param remoteName the name to use for the remote repository * @param uri the uri of the remote repository * @param repository the repository to add the remote to * @throws URISyntaxException the uRI syntax exception * @throws MalformedURLException the malformed url exception * @throws IOException Signals that an I/O exception has occurred. */ public static void addRemoteTo(String remoteName, URIish uri, Repository repository) throws URISyntaxException, MalformedURLException, IOException { StoredConfig config = repository.getConfig(); RemoteConfig remoteConfig = new RemoteConfig(config, remoteName); remoteConfig.addURI(uri); remoteConfig.update(config); config.save(); }
private void testFetchFromOrigin(boolean useRemote) throws Exception { Activator.getDefault().getRepositoryUtil().addConfiguredRepository(clonedRepositoryFile); Activator.getDefault().getRepositoryUtil().addConfiguredRepository(clonedRepositoryFile2); Repository repository = lookupRepository(clonedRepositoryFile2); // add the configuration for push from cloned2 repository.getConfig().setString("remote", "origin", "push", "refs/heads/*:refs/heads/*"); repository.getConfig().save(); SWTBotTree tree = getOrOpenView().bot().tree(); String destinationString = clonedRepositoryFile.getParentFile().getName() + " - " + "origin"; String dialogTitle = NLS.bind(UIText.FetchResultDialog_title, destinationString); selectNode(tree, useRemote, true); runFetch(tree); SWTBotShell confirm = bot.shell(dialogTitle); assertEquals("Wrong result tree row count", 0, confirm.bot().tree().rowCount()); confirm.close(); deleteAllProjects(); shareProjects(clonedRepositoryFile2); String objid = repository.getRef("refs/heads/master").getTarget().getObjectId().name(); objid = objid.substring(0, 7); touchAndSubmit(null); // push from other repository PushOperationUI op = new PushOperationUI(repository, "origin", false); op.start(); String pushdialogTitle = NLS.bind(UIText.PushResultDialog_title, op.getDestinationString()); bot.shell(pushdialogTitle).close(); deleteAllProjects(); refreshAndWait(); selectNode(tree, useRemote, true); runFetch(tree); confirm = bot.shell(dialogTitle); SWTBotTreeItem[] treeItems = confirm.bot().tree().getAllItems(); boolean found = false; for (SWTBotTreeItem item : treeItems) { found = item.getText().contains(objid); if (found) break; } assertTrue(found); confirm.close(); selectNode(tree, useRemote, true); runFetch(tree); confirm = bot.shell(dialogTitle); assertEquals("Wrong result tree row count", 0, confirm.bot().tree().rowCount()); }
public void setConfig(final String category, final String key, final String value) { final Repository repository = getRepository(); try { repository.getConfig().setString(category, null, key, value); repository.getConfig().save(); } catch (final IOException ex) { throw new IllegalStateException("Could not initialize Git repository", ex); } }
private List<Git.Remote> getRemotes(final Repository repository) { Config config = repository.getConfig(); List<Git.Remote> remotes = new ArrayList<Git.Remote>(); for (String remote : config.getSubsections("remote")) { String url = config.getString("remote", remote, "url"); remotes.add(new Git.Remote(remote, url)); } return remotes; }
/** * Creates new branch from a particular start point * * @param name the branch name * @param startPoint valid tree-ish object example: "5c15e8", "master", "HEAD", * "21d5a96070353d01c0f30bc0559ab4de4f5e3ca0" * @throws RefAlreadyExistsException * @throws RefNotFoundException * @throws InvalidRefNameException * @throws GitAPIException */ public void createBranch(String name, String startPoint) throws RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException, GitAPIException { repository.getConfig().setString(BRANCH, name, MERGE, REFS_HEADS_MASTER); CreateBranchCommand createBranchCommand = git.branchCreate(); createBranchCommand.setName(name); createBranchCommand.setStartPoint(startPoint); createBranchCommand.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM); createBranchCommand.call(); }
/** Clones or pulls the remote repository and returns the directory with the checkout */ public void cloneOrPull(final String repo, final CredentialsProvider credentials) throws Exception { if (!localRepo.exists() && !localRepo.mkdirs()) { throw new IOException("Failed to create local repository"); } File gitDir = new File(localRepo, ".git"); if (!gitDir.exists()) { LOG.info("Cloning remote repo " + repo); CloneCommand command = Git.cloneRepository() .setCredentialsProvider(credentials) .setURI(repo) .setDirectory(localRepo) .setRemote(remoteName); git = command.call(); } else { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder .setGitDir(gitDir) .readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build(); git = new Git(repository); // update the remote repo just in case StoredConfig config = repository.getConfig(); config.setString("remote", remoteName, "url", repo); config.setString( "remote", remoteName, "fetch", "+refs/heads/*:refs/remotes/" + remoteName + "/*"); String branch = "master"; config.setString("branch", branch, "remote", remoteName); config.setString("branch", branch, "merge", "refs/heads/" + branch); try { config.save(); } catch (IOException e) { LOG.error( "Failed to save the git configuration to " + localRepo + " with remote repo: " + repo + ". " + e, e); } // now pull LOG.info("Pulling from remote repo " + repo); git.pull().setCredentialsProvider(credentials).setRebase(true).call(); } }
@Before public void setUp() throws IOException, ConfigInvalidException { MockitoAnnotations.initMocks(this); DfsRepositoryDescription dfsRepositoryDescription = new DfsRepositoryDescription("test"); repository = new UniqueInMemoryRepository(dfsRepositoryDescription); InputStream stream = new FileInputStream(new File("fixtures/repository-config")); StringWriter writer = new StringWriter(); IOUtils.copy(stream, writer); repository.getConfig().fromText(writer.toString()); repository.create(); }
/** * Returns true if the remote git url is defined or the local git repo has a remote url defined */ protected boolean hasRemoteRepo() { if (Strings.isNotBlank(gitUrl)) { return true; } Repository repository = git.getRepository(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", remoteName, "url"); if (Strings.isNotBlank(url)) { return true; } return false; }
/** Sets the defaults for change id and signed off */ public void setDefaults() { createChangeId = repository .getConfig() .getBoolean( ConfigConstants.CONFIG_GERRIT_SECTION, ConfigConstants.CONFIG_KEY_CREATECHANGEID, false); signedOff = org.eclipse.egit.ui.Activator.getDefault() .getPreferenceStore() .getBoolean(UIPreferences.COMMIT_DIALOG_SIGNED_OFF_BY); }
@Test public void emptyRepositoryFormatVersion() throws Exception { Repository r = createWorkRepository(); StoredConfig config = r.getConfig(); config.setString( ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_REPO_FORMAT_VERSION, ""); config.save(); new FileRepository(r.getDirectory()); }
private void saveRemote(final URIish uri) throws URISyntaxException, IOException { final StoredConfig dstcfg = dst.getConfig(); final RemoteConfig rc = new RemoteConfig(dstcfg, remoteName); rc.addURI(uri); rc.addFetchRefSpec( new RefSpec() .setForceUpdate(true) .setSourceDestination( Constants.R_HEADS + "*", // $NON-NLS-1$ Constants.R_REMOTES + remoteName + "/*")); // $NON-NLS-1$ rc.update(dstcfg); dstcfg.save(); }
/** * Returns all the remote configs from the given repository. * * @param repository the repository to retrieve the remote configs of * @return the remote configs that are available on the repository * @throws CoreException */ public static List<RemoteConfig> getAllRemoteConfigs(Repository repository) throws CoreException { if (repository == null) { return Collections.emptyList(); } try { return RemoteConfig.getAllRemoteConfigs(repository.getConfig()); } catch (URISyntaxException e) { throw new CoreException( createStatus( e, "Could not get all remote repositories for repository \"{0}\"", repository.toString())); } }
/** * @param gitConfigFolder e.g. /your/project/root/.git * @return Returns git config remote.origin.url field of the repository located at gitConfigFolder */ public static String getGitRemoteUrl(String gitConfigFolder) throws MojoExecutionException { try { Repository repo = new RepositoryBuilder() .setGitDir(new File(gitConfigFolder)) .readEnvironment() .findGitDir() .build(); Config config = repo.getConfig(); return config.getString("remote", "origin", "url"); } catch (Exception e) { throw new MojoExecutionException( "Error trying to get remote origin url of git repository", e); } }
/** * Create a new pack receive for an open repository. * * @param into the destination repository. */ public ReceivePack(final Repository into) { db = into; walk = new RevWalk(db); final ReceiveConfig cfg = db.getConfig().get(ReceiveConfig.KEY); checkReceivedObjects = cfg.checkReceivedObjects; allowCreates = cfg.allowCreates; allowDeletes = cfg.allowDeletes; allowNonFastForwards = cfg.allowNonFastForwards; allowOfsDelta = cfg.allowOfsDelta; refFilter = RefFilter.DEFAULT; preReceive = PreReceiveHook.NULL; postReceive = PostReceiveHook.NULL; advertisedHaves = new HashSet<ObjectId>(); }
public void testBlameMixedLineEndings() throws Exception { File f = new File(workDir, "f"); String content = ""; for (int i = 0; i < 10000; ++i) { content += i + "\r\n"; } write(f, content); // lets turn autocrlf on StoredConfig cfg = repository.getConfig(); cfg.setString( ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "true"); cfg.save(); File[] files = new File[] {f}; GitClient client = getClient(workDir); client.add(files, NULL_PROGRESS_MONITOR); GitRevisionInfo info = client.commit(files, "commit", null, null, NULL_PROGRESS_MONITOR); content = content.replaceFirst("0", "01"); write(f, content); // it should be up to date again // JGit does not work either: org.eclipse.jgit.api.BlameCommand cmd = new Git(repository).blame(); cmd.setFilePath("f"); BlameResult blameResult = cmd.call(); assertNull(blameResult.getSourceCommit(1)); // stupid workaround for JGit cmd = new Git(repository).blame(); cmd.setFilePath("f"); cmd.setTextComparator(RawTextComparator.WS_IGNORE_TRAILING); blameResult = cmd.call(); assertEquals(info.getRevision(), blameResult.getSourceCommit(1).getName()); GitBlameResult res = client.blame(f, null, NULL_PROGRESS_MONITOR); assertNull(res.getLineDetails(0)); assertLineDetails( f, 1, info.getRevision(), info.getAuthor(), info.getCommitter(), res.getLineDetails(1)); // without autocrlf it should all be modified cfg.setString( ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "false"); cfg.save(); res = client.blame(f, null, NULL_PROGRESS_MONITOR); assertNull(res.getLineDetails(1)); }
protected void doPull() throws MojoExecutionException { // CredentialsProvider cp = getCredentials(); CredentialsProvider cp = null; try { Repository repository = git.getRepository(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", "origin", "url"); if (Strings.isNullOrBlank(url)) { getLog() .info( "No remote repository defined for the git repository at " + getGitBuildPathDescription() + " so not doing a pull"); return; } String branch = repository.getBranch(); String mergeUrl = config.getString("branch", branch, "merge"); if (Strings.isNullOrBlank(mergeUrl)) { getLog() .info( "No merge spec for branch." + branch + ".merge in the git repository at " + getGitBuildPathDescription() + " so not doing a pull"); return; } getLog() .info( "Performing a pull in git repository " + getGitBuildPathDescription() + " on remote URL: " + url); git.pull().setCredentialsProvider(cp).setRebase(true).call(); } catch (Throwable e) { String credText = ""; if (cp instanceof UsernamePasswordCredentialsProvider) {} String message = "Failed to pull from the remote git repo with credentials " + cp + " due: " + e.getMessage() + ". This exception is ignored."; getLog().error(message, e); throw new MojoExecutionException(message, e); } }
@Test public void canAddRemoteRepo() throws Exception { Repository repository = testRepository.getRepository(); String remoteName = "redhat"; String gitUri = "www.redhat.com"; EGitUtils.addRemoteTo(remoteName, gitUri, repository); StoredConfig config = repository.getConfig(); Set<String> subsections = config.getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION); assertEquals(1, subsections.size()); assertTrue(subsections.contains(remoteName)); assertEquals( gitUri, config.getString( ConfigConstants.CONFIG_REMOTE_SECTION, remoteName, ConfigConstants.CONFIG_KEY_URL)); }
@Test public void invalidRepositoryFormatVersion() throws Exception { Repository r = createWorkRepository(); StoredConfig config = r.getConfig(); config.setString( ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_REPO_FORMAT_VERSION, "notanumber"); config.save(); try { new FileRepository(r.getDirectory()); fail("IllegalArgumentException not thrown"); } catch (IllegalArgumentException e) { assertNotNull(e.getMessage()); } }
@Test public void unknownRepositoryFormatVersion() throws Exception { Repository r = createWorkRepository(); StoredConfig config = r.getConfig(); config.setLong( ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_REPO_FORMAT_VERSION, 1); config.save(); try { new FileRepository(r.getDirectory()); fail("IOException not thrown"); } catch (IOException e) { assertNotNull(e.getMessage()); } }
// remove remote private boolean handleDelete( HttpServletRequest request, HttpServletResponse response, String path) throws CoreException, IOException, URISyntaxException, JSONException, ServletException { Path p = new Path(path); if (p.segment(1).equals("file")) { // $NON-NLS-1$ // expected path: /gitapi/remote/{remote}/file/{path} String remoteName = p.segment(0); File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1)); Repository db = new FileRepository(gitDir); StoredConfig config = db.getConfig(); config.unsetSection(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName); config.save(); // TODO: handle result return true; } return false; }
/** * Returns the name of the remote repository for the given branch. If there's no current branch or * no remote configured to it, the default remote is returned ("origin"). * * @param branch the branch * @param repository the repository * @return the remote name */ private static String getRemoteName(String branch, Repository repository) { String remoteName = null; if (ObjectId.isId(branch)) { remoteName = Constants.DEFAULT_REMOTE_NAME; } else { remoteName = repository .getConfig() .getString( ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_REMOTE_SECTION); if (remoteName == null) { remoteName = Constants.DEFAULT_REMOTE_NAME; } } return remoteName; }
@Test public void testCreate_Disabled() throws ServiceNotAuthorizedException, IOException { final StoredConfig cfg = db.getConfig(); cfg.setBoolean("http", null, "getanyfile", false); cfg.save(); try { service.access(new R(null, "1.2.3.4"), db); fail("Created session for anonymous user: null"); } catch (ServiceNotEnabledException e) { // expected not authorized } try { service.access(new R("bob", "1.2.3.4"), db); fail("Created session for user: \"bob\""); } catch (ServiceNotEnabledException e) { // expected not authorized } }
/** * @param local * @param inCore */ protected ResolveMerger(Repository local, boolean inCore) { super(local); SupportedAlgorithm diffAlg = local .getConfig() .getEnum( ConfigConstants.CONFIG_DIFF_SECTION, null, ConfigConstants.CONFIG_KEY_ALGORITHM, SupportedAlgorithm.HISTOGRAM); mergeAlgorithm = new MergeAlgorithm(DiffAlgorithm.getAlgorithm(diffAlg)); commitNames = new String[] {"BASE", "OURS", "THEIRS"}; // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ this.inCore = inCore; if (inCore) { implicitDirCache = false; dircache = DirCache.newInCore(); } else { implicitDirCache = true; } }