Example usage for org.eclipse.jgit.lib Repository getDirectory

List of usage examples for org.eclipse.jgit.lib Repository getDirectory

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository getDirectory.

Prototype


public File getDirectory() 

Source Link

Document

Get local metadata directory

Usage

From source file:actions.DownloadSPDX.java

/**
* Get the files from a given repository on github
* @param slotId The thread where the download is happening
* @param localPath The bigArchive on disk where the files will be placed
* @param location The username/repository identification. We'd
* expect something like triplecheck/reporter
* @return True if everything went ok, false if something went wrong
*//*from  w w  w  . j a v a2  s .c om*/
public Boolean download(final int slotId, final File localPath, final String location) {
    // we can't have any older files
    files.deleteDir(localPath);
    final String REMOTE_URL = "https://github.com/" + location + ".git";
    try {

        Git.cloneRepository().setURI(REMOTE_URL).setDirectory(localPath).call();

        // now open the created repository
        FileRepositoryBuilder builder = new FileRepositoryBuilder();

        Repository repository = builder.setGitDir(localPath).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        System.out.println(slotId + "-> Downloaded repository: " + repository.getDirectory());

        repository.close();

    } catch (Exception ex) {
        Logger.getLogger(Repositories.class.getName()).log(Level.SEVERE, null, ex);
        // we need to add this event on the exception list
        utils_deprecated.files.addTextToFile(fileExceptionHappened, "\n" + location);
        // delete the files if possible
        files.deleteDir(localPath);
        System.out.println(slotId + " !!!! Failed to download: " + location);
        // clean up the slot
        slots[slotId] = false;
        return false;
    }

    System.out.println(slotId + "-> Downloaded: " + location);
    return true;
}

From source file:com.beck.ep.team.git.GitListBuilder.java

License:BSD License

public String[] createList(Shell shell, IProject project) throws Exception {
    error = null;// w  w  w .j a va  2s . co m
    RepositoryMapping mapping = RepositoryMapping.getMapping(project);
    if (mapping == null) {
        error = "Git Repository not found (project: " + project.getName() + ")";
        return null;
    }
    Repository rep = mapping.getRepository();
    String pjPath = project.getLocation().toFile().getAbsolutePath();
    String repPath = rep.getDirectory().getParentFile().getAbsolutePath();
    int cutPrefixLen = 0;
    int pathDiffLen = pjPath.length() - repPath.length();
    if (pathDiffLen > 0) {
        cutPrefixLen = pathDiffLen;//for repositoy is not in "parent folder of project"
    }

    RevWalk rw = new RevWalk(rep);
    TreeWalk tw = new TreeWalk(rep);

    int ignoreOpt = pref.getInt(GitModeMenuMgr.PREF_TYPE_IGNORE, GitModeMenuMgr.IGNORE_EXCLUDE);
    if (ignoreOpt == GitModeMenuMgr.IGNORE_ONLY) {
        String[] sa = listIgnored(rep, rw, tw, cutPrefixLen);
        if (cutPrefixLen > 0) {
            for (int i = 0; i < sa.length; i++) {
                if (sa[i].length() > cutPrefixLen) {
                    sa[i] = sa[i].substring(cutPrefixLen);
                }
            }
        }
        return sa;
    }

    int mode = pref.getInt(GitModeMenuMgr.PREF_TYPE_MODE, GitModeMenuMgr.MODE_BRANCH_HEAD);
    int sourceMode = pref.getInt(GitModeMenuMgr.PREF_TYPE_SOURCE, GitModeMenuMgr.MODE_WORKING_AREA);
    if (mode == sourceMode) {
        return new String[0];
    }
    int index = addTree(mode, shell, rep, rw, tw);
    if (index == -2) {
        return null;
    }
    int stageIndex = -1;
    boolean excludeUntrackOpt = false;
    if (!pref.getBoolean(GitModeMenuMgr.PREF_TYPE_UNTRACK, true)
            && sourceMode == GitModeMenuMgr.MODE_WORKING_AREA) {
        excludeUntrackOpt = true;
        if (mode == GitModeMenuMgr.MODE_STAGING) {
            stageIndex = 0;
        }
    }

    int idx2 = addTree(sourceMode, shell, rep, rw, tw);
    if (excludeUntrackOpt && stageIndex == -1) {
        addTree(GitModeMenuMgr.MODE_STAGING, shell, rep, rw, tw);
        stageIndex = 2;
    }
    // skip ignored resources
    if (ignoreOpt == GitModeMenuMgr.IGNORE_EXCLUDE && (index != -1 || idx2 != -1)) {
        int pos = (index != -1) ? index : idx2;
        NotIgnoredFilter notIgnoredFilter = new NotIgnoredFilter(pos);//index = tw.addTree(?)
        tw.setFilter(notIgnoredFilter);
    }

    tw.setRecursive(true);
    ArrayList<String> sa = new ArrayList<String>();
    while (tw.next()) {
        if (!tw.idEqual(0, 1)) {
            if (excludeUntrackOpt) {
                if (tw.getTree(stageIndex, AbstractTreeIterator.class) == null) {
                    WorkingTreeIterator t = tw.getTree(1, WorkingTreeIterator.class);
                    if (t != null && !t.isEntryIgnored()) {//file is untrack...
                        continue;
                    }
                }
            }
            String relPath = tw.getPathString();
            if (cutPrefixLen > 0 && relPath.length() > cutPrefixLen) {
                relPath = relPath.substring(cutPrefixLen);
            }
            sa.add(relPath);
        }
    }

    return sa.toArray(new String[sa.size()]);
}

From source file:com.genuitec.eclipse.gerrit.tools.dialogs.StableBranchSelectionDialog.java

License:Open Source License

@Override
protected IStatus validate(String property, Object value) {
    if (property.equals(PROP_STABLE_BRANCH)) {
        String branchName = (String) value;
        if (branchName.length() < 1) {
            return createErrorStatus("Select an existing stable branch");
        }/* w w  w  .j ava2s . c o  m*/

        for (Repository repository : repositories) {
            try {
                if (repository.getRef("refs/heads/" + branchName) == null) {
                    return createErrorStatus(
                            "Repository {0} does not have stable branch {1}. Choose a different stable branch.",
                            repository.getDirectory().getParentFile().getName(), branchName);
                }
            } catch (IOException e) {
                GerritToolsPlugin.getDefault().log(e);
                return createErrorStatus("Error: {0}", e.getLocalizedMessage());
            }
        }
    }
    return super.validate(property, value);
}

From source file:com.genuitec.eclipse.gerrit.tools.internal.fbranches.dialogs.CreateFeatureBranchDialog.java

License:Open Source License

@Override
protected IStatus validate(String property, Object value) {
    if (property.equals(PROP_BRANCH_NAME)) {
        String branchName = (String) value;
        String refName = "refs/heads/features/" + userId + "/" + branchName; //$NON-NLS-1$ //$NON-NLS-2$
        if (branchName.length() < 4) {
            return createErrorStatus("Branch name must have at least 4 characters");
        } else if (branchName.endsWith("/") || branchName.startsWith("/")) { //$NON-NLS-1$ //$NON-NLS-2$
            return createErrorStatus("Branch name cannot start or end with ''/''");
        } else if (!Repository.isValidRefName(refName)) {
            return createErrorStatus("Branch name {0} is not allowed", branchName);
        } else/*  w  w w.j a  va2 s.co m*/
            try {
                for (Repository repository : repositories) {
                    if (repository.getRef(refName) != null) {
                        return createErrorStatus(
                                "You already have a feature branch with this name in repository {0}. Choose a different name",
                                repository.getDirectory().getParentFile().getName());
                    }
                }
            } catch (IOException e) {
                GerritToolsPlugin.getDefault().log(e);
                return createErrorStatus("Error: {0}", e.getLocalizedMessage());
            }
    }
    return super.validate(property, value);
}

From source file:com.genuitec.eclipse.gerrit.tools.internal.gps.model.GpsGitRepositoriesConfig.java

License:Open Source License

public void performConfiguration(Map<String, Object> options, SubMonitor monitor) throws CoreException {
    monitor.beginTask("", repo2branch.size() * 2);
    for (Entry<String, RepoSetup> entry : repo2branch.entrySet()) {
        if (monitor.isCanceled())
            return;

        RepoSetup repo = entry.getValue();

        String repositoryName = repo.name;
        String repositoryBranch = repo.branch;
        boolean localBranch = repositoryBranch.startsWith("refs/heads/"); //$NON-NLS-1$
        String branchName = null;
        if (localBranch) {
            branchName = repositoryBranch.substring(11);
        }// w  ww  . j  a v  a2 s.  co  m
        switch (repo.state) {
        case LOCATED:
            org.eclipse.egit.ui.Activator.getDefault().getRepositoryUtil()
                    .addConfiguredRepository(new File(repo.location, ".git")); //$NON-NLS-1$
            break;
        case CLONE:
            monitor.setTaskName("Cloning repository " + repositoryName);
            monitor.subTask("");
            try {
                URIish uri = new URIish(repo.url);
                if (repo.userName != null) {
                    uri = uri.setUser(repo.userName);
                } else {
                    uri = uri.setUser(null);
                }
                CloneOperation co = new CloneOperation(uri, true, null, repo.location, repositoryBranch,
                        "origin", 5000); //$NON-NLS-1$
                co.setCredentialsProvider(new EGitCredentialsProvider());
                co.setCloneSubmodules(true);
                co.run(new SubProgressMonitor(monitor, 0, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));

                org.eclipse.egit.ui.Activator.getDefault().getRepositoryUtil()
                        .addConfiguredRepository(co.getGitDir());

                break;
            } catch (Throwable e) {
                if (e instanceof InvocationTargetException) {
                    e = e.getCause();
                }
                throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                        (e instanceof InterruptedException) ? "Operation cancelled" : e.getMessage(), e));
            }
        default:
        }

        monitor.setTaskName("Preparing repository " + repositoryName);

        Repository repository = RepositoryUtils.getRepositoryForName(repositoryName);
        if (repository == null) {
            throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                    MessageFormat.format(
                            "Cannot continue. A required git repository named {0} is not configured.",
                            repositoryName)));
        }

        monitor.subTask(MessageFormat.format("Checking out branch \"{0}\" of git repository \"{1}\"",
                repositoryBranch, repositoryName));

        if (repositoryBranch != null && repositoryBranch.length() > 0) {
            //checkout the branch
            boolean newBranch = false;
            try {
                Ref ref = repository.getRef(repositoryBranch);
                if (localBranch && ref == null) {
                    String originBranch = "refs/remotes/origin/" + branchName; //$NON-NLS-1$
                    ref = repository.getRef(originBranch);
                    if (ref == null) {
                        try {
                            new Git(repository).fetch().setRemote("origin").call(); //$NON-NLS-1$
                        } catch (Exception e) {
                            throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                                    MessageFormat.format(
                                            "Cannot fetch from remote 'origin' of repository \"{0}\":\n{1}",
                                            repositoryName, e.getMessage(), e)));
                        }
                    }
                    ref = repository.getRef(originBranch);
                    if (ref == null) {
                        throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                                MessageFormat.format("Cannot find branch \"{1}\" in repository \"{0}\".",
                                        repositoryName, originBranch)));
                    }
                    //we need to create the local branch based on remote branch
                    new Git(repository).branchCreate().setName(branchName).setStartPoint(originBranch)
                            .setUpstreamMode(SetupUpstreamMode.TRACK).call();
                    newBranch = true;
                }
                if (monitor.isCanceled())
                    return;

                try {
                    new Git(repository).checkout().setName(repositoryBranch).call();
                } catch (Exception e) {
                    if (options.containsKey(PROP_FORCE_CHECKOUT)
                            && (Boolean) options.get(PROP_FORCE_CHECKOUT)) {
                        //try to reset
                        new Git(repository).reset().setMode(ResetType.HARD).call();

                        //and then checkout again
                        new Git(repository).checkout().setName(repositoryBranch).call();
                    } else {
                        throw e;
                    }
                }

                int fileCount = repository.getDirectory().getParentFile().list().length;
                if (fileCount == 1) {
                    //we need to hard reset the repository - there are no files in it
                    new Git(repository).reset().setMode(ResetType.HARD).call();
                }

            } catch (Exception e) {
                throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                        MessageFormat.format("Cannot checkout branch \"{1}\" of repository \"{0}\":\n{2}",
                                repositoryName, repositoryBranch, e.getMessage(), e)));
            }
            if (monitor.isCanceled())
                return;

            if (localBranch) {
                monitor.subTask(MessageFormat.format("Configuring branch \"{0}\" of git repository \"{1}\"",
                        repositoryBranch, repositoryName));
                try {
                    StoredConfig config = repository.getConfig();

                    if (options.get(PROP_CONFIGURE_PUSH_TO_UPSTREAM) != null
                            && (Boolean) options.get(PROP_CONFIGURE_PUSH_TO_UPSTREAM)) {
                        //configure push to upstream
                        config.setString("remote", "origin", "push", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                                repositoryBranch + ":refs/for/" + branchName); //$NON-NLS-1$
                    }
                    if (newBranch || (options.get(PROP_RECONFIGURE_BRANCH) != null
                            && (Boolean) options.get(PROP_RECONFIGURE_BRANCH))) {
                        config.setString("branch", branchName, "remote", "origin"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                        config.setString("branch", branchName, "merge", repositoryBranch); //$NON-NLS-1$ //$NON-NLS-2$
                        config.setString("branch", branchName, "rebase", "true"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    }
                    config.save();
                } catch (Exception e) {
                    throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                            MessageFormat.format("Cannot configure branch \"{1}\" of repository \"{0}\":\n{2}",
                                    repositoryName, repositoryBranch, e.getMessage(), e)));
                }
            }
            if (monitor.isCanceled())
                return;

            if (options.containsKey(PROP_AUTO_PULL) && (Boolean) options.get(PROP_AUTO_PULL)) {
                monitor.subTask(MessageFormat.format("Pulling branch \"{0}\" from git repository \"{1}\"",
                        repositoryBranch, repositoryName));

                try {
                    new Git(repository).pull().call();
                } catch (Exception e) {
                    throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                            MessageFormat.format("Cannot pull branch \"{1}\" of repository \"{0}\":\n{2}",
                                    repositoryName, repositoryBranch, e.getMessage(), e)));
                }
            }
        }

        monitor.worked(1);
    }

}

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

License:Open Source License

public static GerritClient getGerritClient(Repository gitRepository, SubMonitor monitor) {

    final String gerritURL = getGerritURL(gitRepository);
    if (gerritURL == null) {
        throw new RuntimeException(MessageFormat.format("Cannot detect Gerrit URL of repository {0}",
                gitRepository.getDirectory().toString()));
    }/*from   ww  w  .  j  ava2  s .c o  m*/
    final String defaultUser = RepositoryUtils.getUserId(gitRepository);

    monitor.beginTask("", 1);
    monitor.subTask("locating Gerrit configuration");

    final TaskRepositoryManager[] repoManager = new TaskRepositoryManager[1];

    if (Job.getJobManager().currentJob() != null) {
        Job mylynInitJob = new Job("Initialize Mylyn Task Repository Manager") {
            @Override
            protected IStatus run(IProgressMonitor monitor) {
                repoManager[0] = TasksUiPlugin.getRepositoryManager();
                return Status.OK_STATUS;
            }
        };
        mylynInitJob.schedule();
        while (mylynInitJob.getState() != Job.NONE) {
            Job.getJobManager().currentJob().yieldRule(monitor.newChild(0));
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                //ignore
            }
        }
    }

    if (repoManager[0] == null) {
        repoManager[0] = TasksUiPlugin.getRepositoryManager();
    }

    Set<TaskRepository> repos = repoManager[0].getRepositories(GERRIT_REPO_KIND);

    ReviewsConnector connector = (ReviewsConnector) TasksUiPlugin.getConnector(GERRIT_REPO_KIND);

    GerritClient client = null;

    for (TaskRepository repo : repos) {
        if (repo.getUrl().equals(gerritURL)) {
            client = (GerritClient) connector.getReviewClient(repo);
            break;
        }
    }

    if (client == null) {
        //support weird repo setups
        for (TaskRepository repo : repos) {
            if (repo.getUrl().startsWith(gerritURL)) {
                client = (GerritClient) connector.getReviewClient(repo);
                break;
            }
        }
    }

    if (client == null) {
        TaskRepository repository = new TaskRepository(GERRIT_REPO_KIND, gerritURL);
        repository.setVersion(TaskRepository.NO_VERSION_SPECIFIED);
        repository.setRepositoryLabel(gerritURL);
        repository.setProperty(IRepositoryConstants.PROPERTY_CATEGORY, TaskRepository.CATEGORY_REVIEW);
        repository.removeProperty(GerritConnector.KEY_REPOSITORY_ACCOUNT_ID);
        repository.removeProperty(GerritConnector.KEY_REPOSITORY_AUTH);

        //Authentication
        final Display display = Display.getDefault();
        final String[] password = new String[2];
        display.syncExec(new Runnable() {

            @Override
            public void run() {
                PasswordDialog dialog = new PasswordDialog(
                        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Password required",
                        MessageFormat.format("Provide login and password to access {0}", gerritURL),
                        defaultUser);
                if (dialog.open() == Dialog.OK) {
                    password[0] = dialog.getLogin();
                    password[1] = dialog.getPassword();
                }
            }

        });
        if (password[0] == null) {
            throw new OperationCanceledException();
        }
        AuthenticationCredentials credentials = new AuthenticationCredentials(password[0], password[1]);
        repository.setCredentials(AuthenticationType.REPOSITORY, credentials, true);
        repository.setCredentials(AuthenticationType.HTTP, credentials, true);

        //Proxy
        repository.setDefaultProxyEnabled(true);
        repository.setProperty(TaskRepository.PROXY_HOSTNAME, ""); //$NON-NLS-1$
        repository.setProperty(TaskRepository.PROXY_PORT, ""); //$NON-NLS-1$
        credentials = new AuthenticationCredentials("", ""); //$NON-NLS-1$ //$NON-NLS-2$
        repository.setCredentials(AuthenticationType.PROXY, credentials, true);

        //OpenID
        repository.setProperty(GerritConnector.KEY_REPOSITORY_OPEN_ID_ENABLED, "false"); //$NON-NLS-1$
        repository.setProperty(GerritConnector.KEY_REPOSITORY_OPEN_ID_PROVIDER, ""); //$NON-NLS-1$

        //add repo
        repoManager[0].addRepository(repository);

        //get client
        client = (GerritClient) connector.getReviewClient(repository);

    }
    return client;
}

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

License:Open Source License

public static Repository getRepositoryForName(String name) {
    for (String repo : repositoryUtil.getConfiguredRepositories()) {
        File gitDir = new File(repo);
        if (gitDir.exists()) {
            try {
                Repository repository = repositoryCache.lookupRepository(gitDir);
                if (!repository.isBare() && repository.getDirectory().getParentFile().getName().equals(name)) {
                    return repository;
                }//from  w  w  w. j av a  2  s  .c om
            } catch (IOException e) {
                //ignore
            }
        }
    }
    return null;
}

From source file:com.gitblit.GCExecutor.java

License:Apache License

private boolean isRepositoryIdle(Repository repository) {
    try {// w  w w  . j  a  v  a 2  s.c o  m
        // Read the use count.
        // An idle use count is 2:
        // +1 for being in the cache
        // +1 for the repository parameter in this method
        Field useCnt = Repository.class.getDeclaredField("useCnt");
        useCnt.setAccessible(true);
        int useCount = ((AtomicInteger) useCnt.get(repository)).get();
        return useCount == 2;
    } catch (Exception e) {
        logger.warn(MessageFormat.format("Failed to reflectively determine use count for repository {0}",
                repository.getDirectory().getPath()), e);
    }
    return false;
}

From source file:com.gitblit.LuceneExecutor.java

License:Apache License

/**
 * Returns the Lucene configuration for the specified repository.
 * /*from w ww .  j a v  a 2  s .  c om*/
 * @param repository
 * @return a config object
 */
private FileBasedConfig getConfig(Repository repository) {
    File file = new File(repository.getDirectory(), CONF_FILE);
    FileBasedConfig config = new FileBasedConfig(file, FS.detect());
    return config;
}

From source file:com.gitblit.manager.RepositoryManager.java

License:Apache License

/**
 * Create a repository model from the configuration and repository data.
 *
 * @param repositoryName//w ww .  ja va 2 s.c  om
 * @return a repositoryModel or null if the repository does not exist
 */
private RepositoryModel loadRepositoryModel(String repositoryName) {
    Repository r = getRepository(repositoryName);
    if (r == null) {
        return null;
    }
    RepositoryModel model = new RepositoryModel();
    model.isBare = r.isBare();
    File basePath = getRepositoriesFolder();
    if (model.isBare) {
        model.name = com.gitblit.utils.FileUtils.getRelativePath(basePath, r.getDirectory());
    } else {
        model.name = com.gitblit.utils.FileUtils.getRelativePath(basePath, r.getDirectory().getParentFile());
    }
    if (StringUtils.isEmpty(model.name)) {
        // Repository is NOT located relative to the base folder because it
        // is symlinked.  Use the provided repository name.
        model.name = repositoryName;
    }
    model.projectPath = StringUtils.getFirstPathElement(repositoryName);

    StoredConfig config = r.getConfig();
    boolean hasOrigin = false;

    if (config != null) {
        // Initialize description from description file
        hasOrigin = !StringUtils.isEmpty(config.getString("remote", "origin", "url"));
        if (getConfig(config, "description", null) == null) {
            File descFile = new File(r.getDirectory(), "description");
            if (descFile.exists()) {
                String desc = com.gitblit.utils.FileUtils.readContent(descFile,
                        System.getProperty("line.separator"));
                if (!desc.toLowerCase().startsWith("unnamed repository")) {
                    config.setString(Constants.CONFIG_GITBLIT, null, "description", desc);
                }
            }
        }
        model.description = getConfig(config, "description", "");
        model.originRepository = getConfig(config, "originRepository", null);
        model.addOwners(ArrayUtils.fromString(getConfig(config, "owner", "")));
        model.acceptNewPatchsets = getConfig(config, "acceptNewPatchsets", true);
        model.acceptNewTickets = getConfig(config, "acceptNewTickets", true);
        model.requireApproval = getConfig(config, "requireApproval",
                settings.getBoolean(Keys.tickets.requireApproval, false));
        model.mergeTo = getConfig(config, "mergeTo", null);
        model.mergeType = MergeType
                .fromName(getConfig(config, "mergeType", settings.getString(Keys.tickets.mergeType, null)));
        model.useIncrementalPushTags = getConfig(config, "useIncrementalPushTags", false);
        model.incrementalPushTagPrefix = getConfig(config, "incrementalPushTagPrefix", null);
        model.allowForks = getConfig(config, "allowForks", true);
        model.accessRestriction = AccessRestrictionType.fromName(getConfig(config, "accessRestriction",
                settings.getString(Keys.git.defaultAccessRestriction, "PUSH")));
        model.authorizationControl = AuthorizationControl.fromName(getConfig(config, "authorizationControl",
                settings.getString(Keys.git.defaultAuthorizationControl, null)));
        model.verifyCommitter = getConfig(config, "verifyCommitter", false);
        model.showRemoteBranches = getConfig(config, "showRemoteBranches", hasOrigin);
        model.isFrozen = getConfig(config, "isFrozen", false);
        model.skipSizeCalculation = getConfig(config, "skipSizeCalculation", false);
        model.skipSummaryMetrics = getConfig(config, "skipSummaryMetrics", false);
        model.commitMessageRenderer = CommitMessageRenderer.fromName(getConfig(config, "commitMessageRenderer",
                settings.getString(Keys.web.commitMessageRenderer, null)));
        model.federationStrategy = FederationStrategy.fromName(getConfig(config, "federationStrategy", null));
        model.federationSets = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "federationSets")));
        model.isFederated = getConfig(config, "isFederated", false);
        model.gcThreshold = getConfig(config, "gcThreshold",
                settings.getString(Keys.git.defaultGarbageCollectionThreshold, "500KB"));
        model.gcPeriod = getConfig(config, "gcPeriod",
                settings.getInteger(Keys.git.defaultGarbageCollectionPeriod, 7));
        try {
            model.lastGC = new SimpleDateFormat(Constants.ISO8601)
                    .parse(getConfig(config, "lastGC", "1970-01-01'T'00:00:00Z"));
        } catch (Exception e) {
            model.lastGC = new Date(0);
        }
        model.maxActivityCommits = getConfig(config, "maxActivityCommits",
                settings.getInteger(Keys.web.maxActivityCommits, 0));
        model.origin = config.getString("remote", "origin", "url");
        if (model.origin != null) {
            model.origin = model.origin.replace('\\', '/');
            model.isMirror = config.getBoolean("remote", "origin", "mirror", false);
        }
        model.preReceiveScripts = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "preReceiveScript")));
        model.postReceiveScripts = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "postReceiveScript")));
        model.mailingLists = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "mailingList")));
        model.indexedBranches = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "indexBranch")));
        model.metricAuthorExclusions = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "metricAuthorExclusions")));

        // Custom defined properties
        model.customFields = new LinkedHashMap<String, String>();
        for (String aProperty : config.getNames(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS)) {
            model.customFields.put(aProperty,
                    config.getString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, aProperty));
        }
    }
    model.HEAD = JGitUtils.getHEADRef(r);
    if (StringUtils.isEmpty(model.mergeTo)) {
        model.mergeTo = model.HEAD;
    }
    model.availableRefs = JGitUtils.getAvailableHeadTargets(r);
    model.sparkleshareId = JGitUtils.getSparkleshareId(r);
    model.hasCommits = JGitUtils.hasCommits(r);
    updateLastChangeFields(r, model);
    r.close();

    if (StringUtils.isEmpty(model.originRepository) && model.origin != null
            && model.origin.startsWith("file://")) {
        // repository was cloned locally... perhaps as a fork
        try {
            File folder = new File(new URI(model.origin));
            String originRepo = com.gitblit.utils.FileUtils.getRelativePath(getRepositoriesFolder(), folder);
            if (!StringUtils.isEmpty(originRepo)) {
                // ensure origin still exists
                File repoFolder = new File(getRepositoriesFolder(), originRepo);
                if (repoFolder.exists()) {
                    model.originRepository = originRepo.toLowerCase();

                    // persist the fork origin
                    updateConfiguration(r, model);
                }
            }
        } catch (URISyntaxException e) {
            logger.error("Failed to determine fork for " + model, e);
        }
    }
    return model;
}