Search in sources :

Example 1 with Repository

use of org.locationtech.geogig.repository.Repository in project GeoGig by boundlessgeo.

the class RebuildGraphOp method _call.

/**
     * Executes the {@code RebuildGraphOp} operation.
     * 
     * @return a list of {@link ObjectId}s that were found to be missing or incomplete
     */
@Override
protected ImmutableList<ObjectId> _call() {
    Repository repository = repository();
    Preconditions.checkState(!repository.isSparse(), "Cannot rebuild the graph of a sparse repository.");
    List<ObjectId> updated = new LinkedList<ObjectId>();
    ImmutableList<Ref> branches = command(BranchListOp.class).setLocal(true).setRemotes(true).call();
    GraphDatabase graphDb = repository.graphDatabase();
    for (Ref ref : branches) {
        Iterator<RevCommit> commits = command(LogOp.class).setUntil(ref.getObjectId()).call();
        while (commits.hasNext()) {
            RevCommit next = commits.next();
            if (graphDb.put(next.getId(), next.getParentIds())) {
                updated.add(next.getId());
            }
        }
    }
    return ImmutableList.copyOf(updated);
}
Also used : Repository(org.locationtech.geogig.repository.Repository) Ref(org.locationtech.geogig.api.Ref) ObjectId(org.locationtech.geogig.api.ObjectId) GraphDatabase(org.locationtech.geogig.storage.GraphDatabase) BranchListOp(org.locationtech.geogig.api.porcelain.BranchListOp) LinkedList(java.util.LinkedList) RevCommit(org.locationtech.geogig.api.RevCommit)

Example 2 with Repository

use of org.locationtech.geogig.repository.Repository in project GeoGig by boundlessgeo.

the class SendPack method getRemoteRepo.

/**
     * @param remote the remote to get
     * @return an interface for the remote repository
     */
@VisibleForTesting
public Optional<IRemoteRepo> getRemoteRepo(Remote remote) {
    Hints remoteHints = new Hints();
    remoteHints.set(Hints.REMOTES_READ_ONLY, Boolean.FALSE);
    Repository localRepository = repository();
    DeduplicationService deduplicationService = context.deduplicationService();
    return RemoteUtils.newRemote(GlobalContextBuilder.builder.build(remoteHints), remote, localRepository, deduplicationService);
}
Also used : Repository(org.locationtech.geogig.repository.Repository) Hints(org.locationtech.geogig.repository.Hints) DeduplicationService(org.locationtech.geogig.storage.DeduplicationService) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 3 with Repository

use of org.locationtech.geogig.repository.Repository in project GeoGig by boundlessgeo.

the class Scripting method runJVMScript.

/**
     * Runs a script
     * 
     * @param scriptFile the script file to run
     * @param operation the operation triggering the script, to provide context for the script. This
     *        object might get modified if the script modifies it to alter how the command is called
     *        (for instance, changing the commit message in a commit operation)
     * @throws CannotRunGeogigOperationException
     */
@SuppressWarnings("unchecked")
public static void runJVMScript(AbstractGeoGigOp<?> operation, File scriptFile) throws CannotRunGeogigOperationException {
    checkArgument(scriptFile.exists(), "Script file does not exist %s", scriptFile.getPath());
    LOGGER.info("Running jvm script {}", scriptFile.getAbsolutePath());
    final String filename = scriptFile.getName();
    final String ext = Files.getFileExtension(filename);
    final ScriptEngine engine = factory.getEngineByExtension(ext);
    try {
        Map<String, Object> params = getParamMap(operation);
        engine.put(PARAMS, params);
        Repository repo = operation.command(ResolveRepository.class).call();
        GeoGigAPI api = new GeoGigAPI(repo);
        engine.put(GEOGIG, api);
        engine.eval(new FileReader(scriptFile));
        Object map = engine.get(PARAMS);
        setParamMap((Map<String, Object>) map, operation);
    } catch (ScriptException e) {
        Throwable cause = Throwables.getRootCause(e);
        // TODO: improve this hack to check exception type
        if (cause != e) {
            String msg = cause.getMessage();
            msg = msg.substring(CannotRunGeogigOperationException.class.getName().length() + 2, msg.lastIndexOf("(")).trim();
            msg += " (command aborted by .geogig/hooks/" + scriptFile.getName() + ")";
            throw new CannotRunGeogigOperationException(msg);
        } else {
            throw new CannotRunGeogigOperationException(String.format("Script %s threw an exception: '%s'", scriptFile, e.getMessage()), e);
        }
    } catch (Exception e) {
    }
}
Also used : ScriptException(javax.script.ScriptException) Repository(org.locationtech.geogig.repository.Repository) ResolveRepository(org.locationtech.geogig.api.plumbing.ResolveRepository) FileReader(java.io.FileReader) ResolveRepository(org.locationtech.geogig.api.plumbing.ResolveRepository) ScriptEngine(javax.script.ScriptEngine) IOException(java.io.IOException) ScriptException(javax.script.ScriptException)

Example 4 with Repository

use of org.locationtech.geogig.repository.Repository in project GeoGig by boundlessgeo.

the class CloneOp method _call.

/**
     * Executes the clone operation.
     * 
     * @return {@code null}
     * @see org.locationtech.geogig.api.AbstractGeoGigOp#call()
     */
@Override
protected Void _call() {
    Preconditions.checkArgument(repositoryURL != null && !repositoryURL.isEmpty(), "No repository specified to clone from.");
    Repository repository = repository();
    if (repository.isSparse()) {
        Preconditions.checkArgument(branch.isPresent(), "No branch specified for sparse clone.");
    }
    ProgressListener progressListener = getProgressListener();
    progressListener.started();
    // Set up origin
    Remote remote = command(RemoteAddOp.class).setName("origin").setURL(repositoryURL).setMapped(repository.isSparse()).setUserName(username).setPassword(password).setBranch(repository.isSparse() ? branch.get() : null).call();
    if (!depth.isPresent()) {
        // See if we are cloning a shallow clone. If so, a depth must be specified.
        Optional<IRemoteRepo> remoteRepo = RemoteUtils.newRemote(GlobalContextBuilder.builder.build(Hints.readOnly()), remote, repository, repository.deduplicationService());
        Preconditions.checkState(remoteRepo.isPresent(), "Failed to connect to the remote.");
        IRemoteRepo remoteRepoInstance = remoteRepo.get();
        try {
            remoteRepoInstance.open();
        } catch (IOException e) {
            Throwables.propagate(e);
        }
        try {
            depth = remoteRepoInstance.getDepth();
        } finally {
            try {
                remoteRepoInstance.close();
            } catch (IOException e) {
                Throwables.propagate(e);
            }
        }
    }
    if (depth.isPresent()) {
        command(ConfigOp.class).setAction(ConfigAction.CONFIG_SET).setScope(ConfigScope.LOCAL).setName(Repository.DEPTH_CONFIG_KEY).setValue(depth.get().toString()).call();
    }
    // Fetch remote data
    command(FetchOp.class).setDepth(depth.or(0)).setProgressListener(progressListener).call();
    // Set up remote tracking branches
    final ImmutableSet<Ref> remoteRefs = command(LsRemote.class).retrieveTags(false).setRemote(Suppliers.ofInstance(Optional.of(remote))).call();
    boolean emptyRepo = true;
    for (Ref remoteRef : remoteRefs) {
        if (emptyRepo && !remoteRef.getObjectId().isNull()) {
            emptyRepo = false;
        }
        String branchName = remoteRef.localName();
        if (remoteRef instanceof SymRef) {
            continue;
        }
        if (!command(RefParse.class).setName(Ref.HEADS_PREFIX + branchName).call().isPresent()) {
            command(BranchCreateOp.class).setName(branchName).setSource(remoteRef.getObjectId().toString()).call();
        } else {
            command(UpdateRef.class).setName(Ref.HEADS_PREFIX + branchName).setNewValue(remoteRef.getObjectId()).call();
        }
        command(ConfigOp.class).setAction(ConfigAction.CONFIG_SET).setScope(ConfigScope.LOCAL).setName("branches." + branchName + ".remote").setValue(remote.getName()).call();
        command(ConfigOp.class).setAction(ConfigAction.CONFIG_SET).setScope(ConfigScope.LOCAL).setName("branches." + branchName + ".merge").setValue(Ref.HEADS_PREFIX + remoteRef.localName()).call();
    }
    if (!emptyRepo) {
        // checkout branch
        if (branch.isPresent()) {
            command(CheckoutOp.class).setForce(true).setSource(branch.get()).call();
        } else {
            // checkout the head
            final Optional<Ref> currRemoteHead = command(RefParse.class).setName(Ref.REMOTES_PREFIX + remote.getName() + "/" + Ref.HEAD).call();
            if (currRemoteHead.isPresent() && currRemoteHead.get() instanceof SymRef) {
                final SymRef remoteHeadRef = (SymRef) currRemoteHead.get();
                final String currentBranch = Ref.localName(remoteHeadRef.getTarget());
                command(CheckoutOp.class).setForce(true).setSource(currentBranch).call();
            } else {
            // just leave at default; should be master since we just initialized the repo.
            }
        }
    }
    progressListener.complete();
    return null;
}
Also used : Remote(org.locationtech.geogig.api.Remote) LsRemote(org.locationtech.geogig.api.plumbing.LsRemote) UpdateRef(org.locationtech.geogig.api.plumbing.UpdateRef) IOException(java.io.IOException) Repository(org.locationtech.geogig.repository.Repository) Ref(org.locationtech.geogig.api.Ref) UpdateRef(org.locationtech.geogig.api.plumbing.UpdateRef) SymRef(org.locationtech.geogig.api.SymRef) SymRef(org.locationtech.geogig.api.SymRef) ProgressListener(org.locationtech.geogig.api.ProgressListener) IRemoteRepo(org.locationtech.geogig.remote.IRemoteRepo) LsRemote(org.locationtech.geogig.api.plumbing.LsRemote)

Example 5 with Repository

use of org.locationtech.geogig.repository.Repository in project GeoGig by boundlessgeo.

the class InitOp method callInternal.

private Repository callInternal() {
    final Platform platform = platform();
    final File workingDirectory = platform.pwd();
    final Optional<URL> repoUrl = new ResolveGeogigDir(platform).call();
    final boolean repoExisted = repoUrl.isPresent();
    final File envHome;
    if (repoExisted) {
        // we're at either the repo working dir or a subdirectory of it
        try {
            envHome = new File(repoUrl.get().toURI());
        } catch (URISyntaxException e) {
            throw Throwables.propagate(e);
        }
    } else {
        envHome = new File(workingDirectory, ".geogig");
        if (!envHome.mkdirs()) {
            throw new RuntimeException("Unable to create geogig environment at '" + envHome.getAbsolutePath() + "'");
        }
    }
    Map<String, String> effectiveConfigBuilder = Maps.newTreeMap();
    addDefaults(defaults, effectiveConfigBuilder);
    if (config != null) {
        effectiveConfigBuilder.putAll(config);
    }
    if (filterFile != null) {
        try {
            final String FILTER_FILE = "filter.ini";
            File oldFilterFile = new File(filterFile);
            if (!oldFilterFile.exists()) {
                throw new FileNotFoundException("No filter file found at " + filterFile + ".");
            }
            Optional<URL> envHomeURL = new ResolveGeogigDir(platform).call();
            Preconditions.checkState(envHomeURL.isPresent(), "Not inside a geogig directory");
            final URL url = envHomeURL.get();
            if (!"file".equals(url.getProtocol())) {
                throw new UnsupportedOperationException("Sparse clone works only against file system repositories. " + "Repository location: " + url.toExternalForm());
            }
            File repoDir;
            try {
                repoDir = new File(url.toURI());
            } catch (URISyntaxException e) {
                throw new IllegalStateException("Unable to access directory " + url.toExternalForm(), e);
            }
            File newFilterFile = new File(repoDir, FILTER_FILE);
            Files.copy(oldFilterFile, newFilterFile);
            effectiveConfigBuilder.put("sparse.filter", FILTER_FILE);
        } catch (Exception e) {
            throw new IllegalStateException("Unable to copy filter file at path " + filterFile + " to the new repository.", e);
        }
    }
    try {
        Preconditions.checkState(envHome.toURI().toURL().equals(new ResolveGeogigDir(platform).call().get()));
    } catch (MalformedURLException e) {
        Throwables.propagate(e);
    }
    Repository repository;
    try {
        if (!repoExisted) {
            ConfigDatabase configDB = context.configDatabase();
            try {
                for (Entry<String, String> pair : effectiveConfigBuilder.entrySet()) {
                    String key = pair.getKey();
                    String value = pair.getValue();
                    configDB.put(key, value);
                }
                repository = repository();
                repository.configure();
            } catch (RepositoryConnectionException e) {
                throw new IllegalStateException("Unable to initialize repository for the first time: " + e.getMessage(), e);
            }
        } else {
            repository = repository();
        }
        try {
            repository.open();
            // make sure the repo has the empty tree
            ObjectDatabase objectDatabase = repository.objectDatabase();
            objectDatabase.put(RevTree.EMPTY);
        } catch (RepositoryConnectionException e) {
            throw new IllegalStateException("Error opening repository databases: " + e.getMessage(), e);
        }
        createSampleHooks(envHome);
    } catch (ConfigException e) {
        throw e;
    } catch (RuntimeException e) {
        Throwables.propagateIfInstanceOf(e, IllegalStateException.class);
        throw new IllegalStateException("Can't access repository at '" + envHome.getAbsolutePath() + "'", e);
    }
    if (!repoExisted) {
        try {
            createDefaultRefs();
        } catch (IllegalStateException e) {
            Throwables.propagate(e);
        }
    }
    return repository;
}
Also used : MalformedURLException(java.net.MalformedURLException) Platform(org.locationtech.geogig.api.Platform) ConfigDatabase(org.locationtech.geogig.storage.ConfigDatabase) FileNotFoundException(java.io.FileNotFoundException) URISyntaxException(java.net.URISyntaxException) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) RepositoryConnectionException(org.locationtech.geogig.repository.RepositoryConnectionException) RepositoryConnectionException(org.locationtech.geogig.repository.RepositoryConnectionException) Repository(org.locationtech.geogig.repository.Repository) ObjectDatabase(org.locationtech.geogig.storage.ObjectDatabase) ResolveGeogigDir(org.locationtech.geogig.api.plumbing.ResolveGeogigDir) File(java.io.File)

Aggregations

Repository (org.locationtech.geogig.repository.Repository)30 ObjectId (org.locationtech.geogig.api.ObjectId)13 RevCommit (org.locationtech.geogig.api.RevCommit)11 File (java.io.File)10 IOException (java.io.IOException)9 Ref (org.locationtech.geogig.api.Ref)9 UpdateRef (org.locationtech.geogig.api.plumbing.UpdateRef)9 DiffEntry (org.locationtech.geogig.api.plumbing.diff.DiffEntry)8 GeoGIG (org.locationtech.geogig.api.GeoGIG)7 UpdateSymRef (org.locationtech.geogig.api.plumbing.UpdateSymRef)7 SymRef (org.locationtech.geogig.api.SymRef)6 ArrayList (java.util.ArrayList)5 NodeRef (org.locationtech.geogig.api.NodeRef)5 Conflict (org.locationtech.geogig.api.plumbing.merge.Conflict)5 CommitBuilder (org.locationtech.geogig.api.CommitBuilder)4 Platform (org.locationtech.geogig.api.Platform)4 RevObject (org.locationtech.geogig.api.RevObject)4 CanRunDuringConflict (org.locationtech.geogig.di.CanRunDuringConflict)4 LinkedList (java.util.LinkedList)3 RevTree (org.locationtech.geogig.api.RevTree)3