Search in sources :

Example 26 with FileBasedConfig

use of org.eclipse.jgit.storage.file.FileBasedConfig in project egit by eclipse.

the class SubmoduleSyncTest method syncSubmodule.

@Test
public void syncSubmodule() throws Exception {
    deleteAllProjects();
    assertProjectExistence(PROJ1, false);
    clearView();
    Activator.getDefault().getRepositoryUtil().addConfiguredRepository(repositoryFile);
    shareProjects(repositoryFile);
    assertProjectExistence(PROJ1, true);
    refreshAndWait();
    assertHasRepo(repositoryFile);
    Repository repo = lookupRepository(repositoryFile);
    SubmoduleAddCommand command = new SubmoduleAddCommand(repo);
    String path = "sub";
    command.setPath(path);
    String uri = new URIish(repo.getDirectory().toURI().toString()).toString();
    command.setURI(uri);
    Repository subRepo = command.call();
    assertNotNull(subRepo);
    subRepo.close();
    String newUri = "git://server/repo.git";
    File modulesFile = new File(repo.getWorkTree(), Constants.DOT_GIT_MODULES);
    FileBasedConfig config = new FileBasedConfig(modulesFile, repo.getFS());
    config.load();
    config.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_URL, newUri);
    config.save();
    assertEquals(uri, repo.getConfig().getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_URL));
    assertEquals(uri, subRepo.getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, ConfigConstants.CONFIG_KEY_URL));
    refreshAndWait();
    SWTBotTree tree = getOrOpenView().bot().tree();
    TestUtil.expandAndWait(tree.getAllItems()[0]).getNode(UIText.RepositoriesViewLabelProvider_SubmodulesNodeText).select();
    ContextMenuHelper.clickContextMenuSync(tree, myUtil.getPluginLocalizedValue(SYNC_SUBMODULE_CONTEXT_MENU_LABEL));
    TestUtil.joinJobs(JobFamilies.SUBMODULE_SYNC);
    refreshAndWait();
    assertEquals(newUri, repo.getConfig().getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_URL));
    assertEquals(newUri, subRepo.getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, ConfigConstants.CONFIG_KEY_URL));
}
Also used : URIish(org.eclipse.jgit.transport.URIish) Repository(org.eclipse.jgit.lib.Repository) SubmoduleAddCommand(org.eclipse.jgit.api.SubmoduleAddCommand) SWTBotTree(org.eclipse.swtbot.swt.finder.widgets.SWTBotTree) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) File(java.io.File) Test(org.junit.Test)

Example 27 with FileBasedConfig

use of org.eclipse.jgit.storage.file.FileBasedConfig in project egit by eclipse.

the class ReportingTypedConfigGetter method warn.

private static void warn(Config config, String entry, String defaultValue, Throwable cause) {
    String location = null;
    if (config instanceof FileBasedConfig) {
        File file = ((FileBasedConfig) config).getFile();
        location = file.getAbsolutePath();
    }
    Activator.logWarning(msg(location, entry, defaultValue), cause);
}
Also used : FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) File(java.io.File)

Example 28 with FileBasedConfig

use of org.eclipse.jgit.storage.file.FileBasedConfig in project egit by eclipse.

the class ConfigurationEditorComponent method createContents.

/**
 * @return the control being created
 */
public Control createContents() {
    final Composite main = new Composite(parent, SWT.NONE);
    main.setLayout(new GridLayout(2, false));
    GridDataFactory.fillDefaults().grab(true, true).applyTo(main);
    if (editableConfig instanceof FileBasedConfig) {
        Composite locationPanel = new Composite(main, SWT.NONE);
        GridLayout locationLayout = new GridLayout(3, false);
        locationLayout.marginWidth = 0;
        locationPanel.setLayout(locationLayout);
        GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(locationPanel);
        Label locationLabel = new Label(locationPanel, SWT.NONE);
        locationLabel.setText(UIText.ConfigurationEditorComponent_ConfigLocationLabel);
        // GridDataFactory.fillDefaults().applyTo(locationLabel);
        int locationStyle = SWT.BORDER | SWT.READ_ONLY;
        location = new Text(locationPanel, locationStyle);
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(location);
        Button openEditor = new Button(locationPanel, SWT.PUSH);
        openEditor.setText(UIText.ConfigurationEditorComponent_OpenEditorButton);
        openEditor.setToolTipText(UIText.ConfigurationEditorComponent_OpenEditorTooltip);
        openEditor.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                IFileStore store = EFS.getLocalFileSystem().getStore(new Path(((FileBasedConfig) editableConfig).getFile().getAbsolutePath()));
                try {
                    IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), new FileStoreEditorInput(store), EditorsUI.DEFAULT_TEXT_EDITOR_ID);
                } catch (PartInitException ex) {
                    Activator.handleError(ex.getMessage(), ex, true);
                }
            }
        });
        openEditor.setEnabled(((FileBasedConfig) editableConfig).getFile() != null);
    }
    tv = new TreeViewer(main, SWT.SINGLE | SWT.FULL_SELECTION | SWT.BORDER);
    Tree tree = tv.getTree();
    GridDataFactory.fillDefaults().hint(100, 60).grab(true, true).applyTo(tree);
    TreeColumn key = new TreeColumn(tree, SWT.NONE);
    key.setText(UIText.ConfigurationEditorComponent_KeyColumnHeader);
    key.setWidth(150);
    final TextCellEditor editor = new TextCellEditor(tree);
    editor.setValidator(new ICellEditorValidator() {

        @Override
        public String isValid(Object value) {
            String editedValue = value.toString();
            return editedValue.length() > 0 ? null : UIText.ConfigurationEditorComponent_EmptyStringNotAllowed;
        }
    });
    editor.addListener(new ICellEditorListener() {

        @Override
        public void editorValueChanged(boolean oldValidState, boolean newValidState) {
            setErrorMessage(editor.getErrorMessage());
        }

        @Override
        public void cancelEditor() {
            setErrorMessage(null);
        }

        @Override
        public void applyEditorValue() {
            setErrorMessage(null);
        }
    });
    TreeColumn value = new TreeColumn(tree, SWT.NONE);
    value.setText(UIText.ConfigurationEditorComponent_ValueColumnHeader);
    value.setWidth(250);
    new TreeViewerColumn(tv, value).setEditingSupport(new EditingSupport(tv) {

        @Override
        protected void setValue(Object element, Object newValue) {
            Entry entry = (Entry) element;
            if (!entry.value.equals(newValue)) {
                entry.changeValue(newValue.toString());
                markDirty();
            }
        }

        @Override
        protected Object getValue(Object element) {
            return ((Entry) element).value;
        }

        @Override
        protected CellEditor getCellEditor(Object element) {
            return editor;
        }

        @Override
        protected boolean canEdit(Object element) {
            return editable && element instanceof Entry;
        }
    });
    tv.setContentProvider(new WorkbenchContentProvider());
    Font defaultFont;
    if (useDialogFont)
        defaultFont = JFaceResources.getDialogFont();
    else
        defaultFont = JFaceResources.getDefaultFont();
    tv.setLabelProvider(new ConfigEditorLabelProvider(defaultFont));
    tree.setHeaderVisible(true);
    tree.setLinesVisible(true);
    Composite buttonPanel = new Composite(main, SWT.NONE);
    GridLayoutFactory.fillDefaults().applyTo(buttonPanel);
    GridDataFactory.fillDefaults().grab(false, false).applyTo(buttonPanel);
    newValue = new Button(buttonPanel, SWT.PUSH);
    GridDataFactory.fillDefaults().applyTo(newValue);
    newValue.setText(UIText.ConfigurationEditorComponent_AddButton);
    newValue.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            String suggestedKey;
            IStructuredSelection sel = (IStructuredSelection) tv.getSelection();
            Object first = sel.getFirstElement();
            if (first instanceof Section)
                suggestedKey = ((Section) first).name + DOT;
            else if (first instanceof SubSection) {
                SubSection sub = (SubSection) first;
                suggestedKey = sub.parent.name + DOT + sub.name + DOT;
            } else if (first instanceof Entry) {
                Entry entry = (Entry) first;
                if (entry.sectionparent != null)
                    suggestedKey = entry.sectionparent.name + DOT;
                else
                    suggestedKey = entry.subsectionparent.parent.name + DOT + entry.subsectionparent.name + DOT;
            } else
                suggestedKey = null;
            AddConfigEntryDialog dlg = new AddConfigEntryDialog(getShell(), suggestedKey);
            if (dlg.open() == Window.OK) {
                String result = dlg.getKey();
                if (result == null) {
                    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=472110
                    return;
                }
                StringTokenizer st = new StringTokenizer(result, DOT);
                if (st.countTokens() == 2) {
                    String sectionName = st.nextToken();
                    String entryName = st.nextToken();
                    Entry entry = ((GitConfig) tv.getInput()).getEntry(sectionName, null, entryName);
                    if (entry == null)
                        editableConfig.setString(sectionName, null, entryName, dlg.getValue());
                    else
                        entry.addValue(dlg.getValue());
                    markDirty();
                } else if (st.countTokens() > 2) {
                    int n = st.countTokens();
                    String sectionName = st.nextToken();
                    StringBuilder b = new StringBuilder(st.nextToken());
                    for (int i = 0; i < n - 3; i++) {
                        b.append(DOT);
                        b.append(st.nextToken());
                    }
                    String subSectionName = b.toString();
                    String entryName = st.nextToken();
                    Entry entry = ((GitConfig) tv.getInput()).getEntry(sectionName, subSectionName, entryName);
                    if (entry == null)
                        editableConfig.setString(sectionName, subSectionName, entryName, dlg.getValue());
                    else
                        entry.addValue(dlg.getValue());
                    markDirty();
                } else
                    Activator.handleError(UIText.ConfigurationEditorComponent_WrongNumberOfTokensMessage, null, true);
            }
        }
    });
    remove = new Button(buttonPanel, SWT.PUSH);
    GridDataFactory.fillDefaults().applyTo(remove);
    remove.setText(UIText.ConfigurationEditorComponent_RemoveButton);
    remove.setToolTipText(UIText.ConfigurationEditorComponent_RemoveTooltip);
    remove.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            IStructuredSelection sel = (IStructuredSelection) tv.getSelection();
            Object first = sel.getFirstElement();
            if (first instanceof Section) {
                Section section = (Section) first;
                if (MessageDialog.openConfirm(getShell(), UIText.ConfigurationEditorComponent_RemoveSectionTitle, NLS.bind(UIText.ConfigurationEditorComponent_RemoveSectionMessage, section.name))) {
                    editableConfig.unsetSection(section.name, null);
                    markDirty();
                }
            } else if (first instanceof SubSection) {
                SubSection section = (SubSection) first;
                if (MessageDialog.openConfirm(getShell(), UIText.ConfigurationEditorComponent_RemoveSubsectionTitle, NLS.bind(UIText.ConfigurationEditorComponent_RemoveSubsectionMessage, section.parent.name + DOT + section.name))) {
                    editableConfig.unsetSection(section.parent.name, section.name);
                    markDirty();
                }
            } else if (first instanceof Entry) {
                ((Entry) first).removeValue();
                markDirty();
            }
            super.widgetSelected(e);
        }
    });
    tv.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            updateEnablement();
        }
    });
    initControlsFromConfig();
    contents = main;
    return contents;
}
Also used : TreeViewer(org.eclipse.jface.viewers.TreeViewer) CellEditor(org.eclipse.jface.viewers.CellEditor) TextCellEditor(org.eclipse.jface.viewers.TextCellEditor) Label(org.eclipse.swt.widgets.Label) EditingSupport(org.eclipse.jface.viewers.EditingSupport) SelectionChangedEvent(org.eclipse.jface.viewers.SelectionChangedEvent) IStructuredSelection(org.eclipse.jface.viewers.IStructuredSelection) Font(org.eclipse.swt.graphics.Font) GridLayout(org.eclipse.swt.layout.GridLayout) ICellEditorListener(org.eclipse.jface.viewers.ICellEditorListener) Button(org.eclipse.swt.widgets.Button) TreeColumn(org.eclipse.swt.widgets.TreeColumn) SelectionEvent(org.eclipse.swt.events.SelectionEvent) Tree(org.eclipse.swt.widgets.Tree) PartInitException(org.eclipse.ui.PartInitException) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) Path(org.eclipse.core.runtime.Path) Composite(org.eclipse.swt.widgets.Composite) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) ISelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) Text(org.eclipse.swt.widgets.Text) UIText(org.eclipse.egit.ui.internal.UIText) WorkbenchContentProvider(org.eclipse.ui.model.WorkbenchContentProvider) TreeViewerColumn(org.eclipse.jface.viewers.TreeViewerColumn) StringTokenizer(java.util.StringTokenizer) ICellEditorValidator(org.eclipse.jface.viewers.ICellEditorValidator) IFileStore(org.eclipse.core.filesystem.IFileStore) TextCellEditor(org.eclipse.jface.viewers.TextCellEditor) FileStoreEditorInput(org.eclipse.ui.ide.FileStoreEditorInput)

Example 29 with FileBasedConfig

use of org.eclipse.jgit.storage.file.FileBasedConfig in project egit by eclipse.

the class ConfigurationEditorComponent method initControlsFromConfig.

private void initControlsFromConfig() {
    try {
        editableConfig.load();
        tv.setInput(new GitConfig(editableConfig));
        editable = true;
        if (editableConfig instanceof FileBasedConfig) {
            FileBasedConfig fileConfig = (FileBasedConfig) editableConfig;
            File configFile = fileConfig.getFile();
            if (configFile != null)
                if (isWriteable(configFile))
                    location.setText(configFile.getPath());
                else {
                    location.setText(NLS.bind(UIText.ConfigurationEditorComponent_ReadOnlyLocationFormat, configFile.getPath()));
                    editable = false;
                }
            else {
                location.setText(UIText.ConfigurationEditorComponent_NoConfigLocationKnown);
                editable = false;
            }
        }
    } catch (IOException e) {
        Activator.handleError(e.getMessage(), e, true);
    } catch (ConfigInvalidException e) {
        Activator.handleError(e.getMessage(), e, true);
    }
    tv.expandAll();
    updateEnablement();
}
Also used : ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) IOException(java.io.IOException) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) File(java.io.File)

Example 30 with FileBasedConfig

use of org.eclipse.jgit.storage.file.FileBasedConfig in project bndtools by bndtools.

the class GitUtils method getRepository.

public static synchronized Repository getRepository(File gitRoot, String branch, String gitUrl, String gitPushUrl) throws IOException, ConfigInvalidException, JGitInternalException, GitAPIException {
    File dotGit;
    if (gitRoot.getName().equals(Constants.DOT_GIT)) {
        dotGit = gitRoot;
    } else {
        dotGit = new File(gitRoot, Constants.DOT_GIT);
    }
    Repository repository = localRepos.get(dotGit);
    if (repository != null && dotGit.exists()) {
        return repository;
    }
    if (!dotGit.exists()) {
        Git.cloneRepository().setDirectory(gitRoot).setCloneAllBranches(true).setURI(gitUrl).call();
        FileBasedConfig config = new FileBasedConfig(new File(dotGit, "config"), FS.DETECTED);
        config.load();
        if (gitPushUrl != null) {
            config.setString(ConfigConstants.CONFIG_REMOTE_SECTION, "origin", "pushurl", gitPushUrl);
        }
        config.save();
    }
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    repository = builder.setGitDir(dotGit).readEnvironment().findGitDir().build();
    localRepos.put(dotGit, repository);
    try {
        repository.incrementOpen();
        Git git = Git.wrap(repository);
        // Check branch
        boolean pull = true;
        String currentBranch = repository.getBranch();
        if (branch != null && !branch.equals(currentBranch)) {
            CheckoutCommand checkout = git.checkout();
            if (!branchExists(git, branch)) {
                checkout.setCreateBranch(true);
                pull = false;
            }
            checkout.setName(branch);
            checkout.call();
        }
        if (pull) {
            git.pull().call();
        } else {
            git.fetch().call();
        }
    } catch (Exception e) {
        if (!(e.getCause() instanceof TransportException)) {
            throw new RuntimeException(e);
        }
    } finally {
        if (repository != null) {
            repository.close();
        }
    }
    return repository;
}
Also used : Repository(org.eclipse.jgit.lib.Repository) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) Git(org.eclipse.jgit.api.Git) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) File(java.io.File) FileRepositoryBuilder(org.eclipse.jgit.storage.file.FileRepositoryBuilder) TransportException(org.eclipse.jgit.errors.TransportException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) TransportException(org.eclipse.jgit.errors.TransportException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException)

Aggregations

FileBasedConfig (org.eclipse.jgit.storage.file.FileBasedConfig)47 File (java.io.File)19 IOException (java.io.IOException)15 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)12 Config (org.eclipse.jgit.lib.Config)10 FS (org.eclipse.jgit.util.FS)7 Test (org.junit.Test)7 StoredConfig (org.eclipse.jgit.lib.StoredConfig)6 Path (java.nio.file.Path)5 Repository (org.eclipse.jgit.lib.Repository)5 SitePaths (com.google.gerrit.server.config.SitePaths)4 HashMap (java.util.HashMap)4 UserModel (com.gitblit.models.UserModel)3 FileBasedAllProjectsConfigProvider (com.google.gerrit.server.config.FileBasedAllProjectsConfigProvider)3 InputStream (java.io.InputStream)3 ArrayList (java.util.ArrayList)3 ObjectId (org.eclipse.jgit.lib.ObjectId)3 RevCommit (org.eclipse.jgit.revwalk.RevCommit)3 SystemReader (org.eclipse.jgit.util.SystemReader)3 Before (org.junit.Before)3