Example usage for org.eclipse.jgit.util SystemReader getInstance

List of usage examples for org.eclipse.jgit.util SystemReader getInstance

Introduction

In this page you can find the example usage for org.eclipse.jgit.util SystemReader getInstance.

Prototype

public static SystemReader getInstance() 

Source Link

Document

Get the current SystemReader instance

Usage

From source file:com.diffplug.gradle.spotless.GitAttributesLineEndingPolicy.java

License:Apache License

public static GitAttributesLineEndingPolicy create(File rootFolder) {
    return Errors.rethrow().get(() -> {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        builder.findGitDir(rootFolder);/*from  w  w w  .j a  v a 2  s .  c o m*/
        if (builder.getGitDir() != null) {
            // we found a repository, so we can grab all the values we need from it
            Repository repo = builder.build();
            AttributesNodeProvider nodeProvider = repo.createAttributesNodeProvider();
            Function<AttributesNode, List<AttributesRule>> getRules = node -> node == null
                    ? Collections.emptyList()
                    : node.getRules();
            return new GitAttributesLineEndingPolicy(repo.getConfig(),
                    getRules.apply(nodeProvider.getInfoAttributesNode()), repo.getWorkTree(),
                    getRules.apply(nodeProvider.getGlobalAttributesNode()));
        } else {
            // there's no repo, so it takes some work to grab the system-wide values
            Config systemConfig = SystemReader.getInstance().openSystemConfig(null, FS.DETECTED);
            Config userConfig = SystemReader.getInstance().openUserConfig(systemConfig, FS.DETECTED);
            if (userConfig == null) {
                userConfig = new Config();
            }

            List<AttributesRule> globalRules = Collections.emptyList();
            // copy-pasted from org.eclipse.jgit.lib.CoreConfig
            String globalAttributesPath = userConfig.getString(ConfigConstants.CONFIG_CORE_SECTION, null,
                    ConfigConstants.CONFIG_KEY_ATTRIBUTESFILE);
            // copy-pasted from org.eclipse.jgit.internal.storage.file.GlobalAttributesNode
            if (globalAttributesPath != null) {
                FS fs = FS.detect();
                File attributesFile;
                if (globalAttributesPath.startsWith("~/")) { //$NON-NLS-1$
                    attributesFile = fs.resolve(fs.userHome(), globalAttributesPath.substring(2));
                } else {
                    attributesFile = fs.resolve(null, globalAttributesPath);
                }
                globalRules = parseRules(attributesFile);
            }
            return new GitAttributesLineEndingPolicy(userConfig,
                    // no git info file
                    Collections.emptyList(), null, globalRules);
        }
    });
}

From source file:com.genuitec.eclipse.gerrit.tools.utils.RepositoryUtils.java

License:Open Source License

public static String getUserId(Repository repository) {
    StoredConfig config;/* w  w  w .  j ava 2  s .  c om*/
    if (repository == null) {
        if (StringUtils.isEmptyOrNull(SystemReader.getInstance().getenv(Constants.GIT_CONFIG_NOSYSTEM_KEY))) {
            config = SystemReader.getInstance().openSystemConfig(null, FS.DETECTED);
        } else {
            config = new FileBasedConfig(null, FS.DETECTED) {
                public void load() {
                    // empty, do not load
                }

                public boolean isOutdated() {
                    // regular class would bomb here
                    return false;
                }
            };
        }
        try {
            config.load();
            config = SystemReader.getInstance().openUserConfig(config, FS.DETECTED);
            config.load();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    } else {
        config = repository.getConfig();
    }
    String email = config.getString("user", null, "email"); //$NON-NLS-1$ //$NON-NLS-2$
    if (email != null) {
        int ind = email.indexOf('@');
        if (ind > 0) {
            return email.substring(0, ind);
        }
    }
    return null;
}

From source file:com.gitblit.transport.ssh.commands.SshCommand.java

License:Apache License

protected String getHostname() {
    IGitblit gitblit = getContext().getGitblit();
    String host = null;/* www  . jav a2s.c  om*/
    String url = gitblit.getSettings().getString(Keys.web.canonicalUrl, "https://localhost:8443");
    if (url != null) {
        try {
            host = new URL(url).getHost();
        } catch (MalformedURLException e) {
        }
    }
    if (StringUtils.isEmpty(host)) {
        host = SystemReader.getInstance().getHostname();
    }
    return host;
}

From source file:com.google.gerrit.pgm.init.api.InitUtil.java

License:Apache License

public static String hostname() {
    return SystemReader.getInstance().getHostname();
}

From source file:com.google.gerrit.pgm.init.InitUtil.java

License:Apache License

static String hostname() {
    return SystemReader.getInstance().getHostname();
}

From source file:com.google.gerrit.server.git.validators.CommitValidators.java

License:Apache License

/**
 * Get the Gerrit hostname.//  w  w w  . j a  v  a2  s .  c om
 *
 * @return the hostname from the canonical URL if it is configured, otherwise
 *         whatever the OS says the hostname is.
 */
private static String getGerritHost(String canonicalWebUrl) {
    String host;
    if (canonicalWebUrl != null) {
        try {
            host = new URL(canonicalWebUrl).getHost();
        } catch (MalformedURLException e) {
            host = SystemReader.getInstance().getHostname();
        }
    } else {
        host = SystemReader.getInstance().getHostname();
    }
    return host;
}

From source file:com.google.gerrit.server.IdentifiedUser.java

License:Apache License

public PersonIdent newCommitterIdent(final Date when, final TimeZone tz) {
    final Account ua = getAccount();
    String name = ua.getFullName();
    String email = ua.getPreferredEmail();

    if (email == null || email.isEmpty()) {
        // No preferred email is configured. Use a generic identity so we
        // don't leak an address the user may have given us, but doesn't
        // necessarily want to publish through Git records.
        ////w  ww.  java 2 s .com
        String user = getUserName();
        if (user == null || user.isEmpty()) {
            user = "account-" + ua.getId().toString();
        }

        String host;
        if (canonicalUrl.get() != null) {
            try {
                host = new URL(canonicalUrl.get()).getHost();
            } catch (MalformedURLException e) {
                host = SystemReader.getInstance().getHostname();
            }
        } else {
            host = SystemReader.getInstance().getHostname();
        }

        email = user + "@" + host;
    }

    if (name == null || name.isEmpty()) {
        final int at = email.indexOf('@');
        if (0 < at) {
            name = email.substring(0, at);
        } else {
            name = anonymousCowardName;
        }
    }

    return new PersonIdent(name, email, when, tz);
}

From source file:com.google.gerrit.server.mail.OutgoingEmail.java

License:Apache License

public String getGerritHost() {
    if (getGerritUrl() != null) {
        try {/*from   w w  w.  j  a  v a  2  s  .  com*/
            return new URL(getGerritUrl()).getHost();
        } catch (MalformedURLException e) {
            // Try something else.
        }
    }

    // Fall back onto whatever the local operating system thinks
    // this server is called. We hopefully didn't get here as a
    // good admin would have configured the canonical url.
    //
    return SystemReader.getInstance().getHostname();
}

From source file:com.google.gerrit.server.schema.Schema_65.java

License:Apache License

@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
    Repository git;/*from  ww w  . j  a  v a 2 s . c om*/
    try {
        git = mgr.openRepository(allProjects);
    } catch (IOException e) {
        throw new OrmException(e);
    }
    try {
        MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allProjects, git);
        ProjectConfig config = ProjectConfig.read(md);
        Map<Integer, ContributorAgreement> agreements = getAgreementToAdd(db, config);
        if (agreements.isEmpty()) {
            return;
        }
        ui.message("Moved contributor agreements to project.config");

        // Create the auto verify groups.
        List<AccountGroup.UUID> adminGroupUUIDs = getAdministrateServerGroups(db, config);
        for (ContributorAgreement agreement : agreements.values()) {
            if (agreement.getAutoVerify() != null) {
                getOrCreateGroupForIndividuals(db, config, adminGroupUUIDs, agreement);
            }
        }

        // Scan AccountAgreement
        long minTime = addAccountAgreements(db, config, adminGroupUUIDs, agreements);

        ProjectConfig base = ProjectConfig.read(md, null);
        for (ContributorAgreement agreement : agreements.values()) {
            base.replace(agreement);
        }
        base.getAccountsSection().setSameGroupVisibility(config.getAccountsSection().getSameGroupVisibility());

        BatchMetaDataUpdate batch = base.openUpdate(md);
        try {
            // Scan AccountGroupAgreement
            List<AccountGroupAgreement> groupAgreements = getAccountGroupAgreements(db, agreements);

            // Find the earliest change
            for (AccountGroupAgreement aga : groupAgreements) {
                minTime = Math.min(minTime, aga.getTime());
            }
            minTime -= 60 * 1000; // 1 Minute

            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(new PersonIdent(serverUser, new Date(minTime)));
            commit.setCommitter(new PersonIdent(serverUser, new Date(minTime)));
            commit.setMessage("Add the ContributorAgreements for upgrade to Gerrit Code Review schema 65\n");
            batch.write(commit);

            for (AccountGroupAgreement aga : groupAgreements) {
                AccountGroup group = db.accountGroups().get(aga.groupId);
                if (group == null) {
                    continue;
                }

                ContributorAgreement agreement = agreements.get(aga.claId);
                agreement.getAccepted().add(new PermissionRule(config.resolve(group)));
                base.replace(agreement);

                PersonIdent ident = null;
                if (aga.reviewedBy != null) {
                    Account ua = db.accounts().get(aga.reviewedBy);
                    if (ua != null) {
                        String name = ua.getFullName();
                        String email = ua.getPreferredEmail();

                        if (email == null || email.isEmpty()) {
                            // No preferred email is configured. Use a generic identity so we
                            // don't leak an address the user may have given us, but doesn't
                            // necessarily want to publish through Git records.
                            //
                            String user = ua.getUserName();
                            if (user == null || user.isEmpty()) {
                                user = "account-" + ua.getId().toString();
                            }

                            String host = SystemReader.getInstance().getHostname();
                            email = user + "@" + host;
                        }

                        if (name == null || name.isEmpty()) {
                            final int at = email.indexOf('@');
                            if (0 < at) {
                                name = email.substring(0, at);
                            } else {
                                name = anonymousCowardName;
                            }
                        }

                        ident = new PersonIdent(name, email, new Date(aga.getTime()), TimeZone.getDefault());
                    }
                }
                if (ident == null) {
                    ident = new PersonIdent(serverUser, new Date(aga.getTime()));
                }

                // Build the commits such that it keeps track of the date added and
                // who added it.
                commit = new CommitBuilder();
                commit.setAuthor(ident);
                commit.setCommitter(new PersonIdent(serverUser, new Date(aga.getTime())));

                String msg = String.format("Accept %s contributor agreement for %s\n", agreement.getName(),
                        group.getName());
                if (!Strings.isNullOrEmpty(aga.reviewComments)) {
                    msg += "\n" + aga.reviewComments + "\n";
                }
                commit.setMessage(msg);
                batch.write(commit);
            }

            // Merge the agreements with the other data in project.config.
            commit = new CommitBuilder();
            commit.setAuthor(serverUser);
            commit.setCommitter(serverUser);
            commit.setMessage("Upgrade to Gerrit Code Review schema 65\n");
            commit.addParentId(config.getRevision());
            batch.write(config, commit);

            // Save the the final metadata.
            batch.commitAt(config.getRevision());
        } finally {
            batch.close();
        }
    } catch (IOException e) {
        throw new OrmException(e);
    } catch (ConfigInvalidException e) {
        throw new OrmException(e);
    } finally {
        git.close();
    }
}

From source file:com.google.gerrit.testutil.TestTimeUtil.java

License:Apache License

/**
 * Set the clock step used by {@link com.google.gerrit.common.TimeUtil}.
 *
 * @param clockStep amount to increment clock by on each lookup.
 * @param clockStepUnit time unit for {@code clockStep}.
 *///w ww  . j av  a 2s.c  o m
public static synchronized void setClockStep(long clockStep, TimeUnit clockStepUnit) {
    checkState(clockMs != null, "call resetWithClockStep first");
    clockStepMs = MILLISECONDS.convert(clockStep, clockStepUnit);
    DateTimeUtils.setCurrentMillisProvider(new MillisProvider() {
        @Override
        public long getMillis() {
            return clockMs.getAndAdd(clockStepMs);
        }
    });

    SystemReader.setInstance(null);
    final SystemReader defaultReader = SystemReader.getInstance();
    SystemReader r = new SystemReader() {
        @Override
        public String getHostname() {
            return defaultReader.getHostname();
        }

        @Override
        public String getenv(String variable) {
            return defaultReader.getenv(variable);
        }

        @Override
        public String getProperty(String key) {
            return defaultReader.getProperty(key);
        }

        @Override
        public FileBasedConfig openUserConfig(Config parent, FS fs) {
            return defaultReader.openUserConfig(parent, fs);
        }

        @Override
        public FileBasedConfig openSystemConfig(Config parent, FS fs) {
            return defaultReader.openSystemConfig(parent, fs);
        }

        @Override
        public long getCurrentTime() {
            return clockMs.getAndAdd(clockStepMs);
        }

        @Override
        public int getTimezone(long when) {
            return defaultReader.getTimezone(when);
        }
    };
    SystemReader.setInstance(r);
}