List of usage examples for org.eclipse.jgit.lib Repository getConfig
@NonNull public abstract StoredConfig getConfig();
From source file:net.morimekta.idltool.IdlUtils.java
License:Apache License
public static String getLocalRemoteName(Repository repository, String remoteName) throws IOException { Config config = repository.getConfig(); String currentBranch = repository.getBranch(); if (currentBranch == null) { throw new RuntimeException("No current branch!"); }/*from w ww . j a v a 2 s.c o m*/ if (remoteName == null) { String branch = config.getString("default", null, "branch"); if (branch == null) { branch = "master"; } remoteName = config.getString("branch", branch, "remote"); if (remoteName == null) { remoteName = config.getString("branch", "master", "remote"); if (remoteName == null) { remoteName = "origin"; } } } String remoteUrl = config.getString("remote", remoteName, "url"); if (remoteUrl == null) { throw new RuntimeException("No URL for remote " + remoteName); } return remoteUrl.replaceAll("^.*://", "").replaceAll("^.*@", "").replaceAll("[.]git$", "").replaceAll(":", "/"); }
From source file:net.polydawn.mdm.commands.MdmReleaseInitCommand.java
License:Open Source License
/** * Writes a new submodule block to the parentRepo's .gitmodules file declaring the * release repo, and initializes the local .git/config file to match. * * @param parentRepo//www . j av a 2 s . c o m * @throws IOException * @throws ConfigInvalidException */ void writeParentGitmoduleConfig(Repository parentRepo) throws IOException, ConfigInvalidException { // write gitmodule config for the new submodule StoredConfig gitmodulesCfg = new FileBasedConfig( new File(parentRepo.getWorkTree(), Constants.DOT_GIT_MODULES), parentRepo.getFS()); gitmodulesCfg.load(); gitmodulesCfg.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_PATH, path); gitmodulesCfg.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_URL, remotePublicUrl); gitmodulesCfg.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, MdmConfigConstants.Module.MODULE_TYPE.toString(), MdmModuleType.RELEASES.toString()); gitmodulesCfg.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_UPDATE, "none"); gitmodulesCfg.save(); // initialize local parent repo config for the submodule MdmModuleRelease module = MdmModuleRelease.load(parentRepo, path, gitmodulesCfg); Plumbing.initLocalConfig(parentRepo, module); parentRepo.getConfig().save(); }
From source file:net.polydawn.mdm.commands.MdmReleaseInitCommand.java
License:Open Source License
/** * Write origin and fetch config into the release module. Only performed when * operating in submodule mode, since otherwise we don't have any requirement to * request a value for {@link #remotePublishUrl}. * * @param releaserepo/*from w ww . ja v a2 s. c o m*/ * @throws IOException */ void writeReleaseRepoConfig(Repository releaserepo) throws IOException { releaserepo.getConfig().setString(ConfigConstants.CONFIG_REMOTE_SECTION, "origin", ConfigConstants.CONFIG_KEY_URL, remotePublishUrl); releaserepo.getConfig().setString(ConfigConstants.CONFIG_REMOTE_SECTION, "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); releaserepo.getConfig().save(); }
From source file:net.polydawn.mdm.MdmModule.java
License:Open Source License
/** * @param repo//from ww w. ja va 2 s.co m * required. * * well, unless you're about to create one, in which case not even. * @param handle * required. * @param parent * null if repository stands alone, otherwise if we are a submodule * required. * @param gitmodulesCfg * ignored if parent null, otherwise required. * @param indexId * ignored if parent null, otherwise will be automatically loaded * if not provided. * * the commit hash known to the parent repo index for this * submodule (or null if it's not handy; we'll load it in that * case). * * @throws MdmModuleTypeException * if the {@code gitmodulesCfg} entries for {@code handle} don't * concur with the {@code type} expected. * @throws MdmRepositoryIOException * if disks reject our advances */ protected MdmModule(Repository repo, String handle, Repository parent, Config gitmodulesCfg, ObjectId indexId) throws MdmRepositoryIOException, MdmModuleTypeException { handle = (File.separatorChar != '/') ? handle.replace(File.separatorChar, '/') : handle; this.handle = handle; this.repo = repo; if (repo == null) { this.headId = null; this.dirtyFiles = false; } else { try { this.headId = repo.resolve(Constants.HEAD); } catch (IOException e) { throw new MdmRepositoryIOException(false, handle, e); } boolean dirtyFiles; try { dirtyFiles = !new Git(repo).status().call().isClean(); } catch (NoWorkTreeException e) { throw new RuntimeException("wat", e); } catch (GitAPIException e) { dirtyFiles = false; } this.dirtyFiles = dirtyFiles; } if (parent != null) { // sanity check the expected module type if we're a submodule (if we're not a submodule, we can't make any such check since there's no gitmodules file to refer to). MdmModuleType type = getType(); MdmModuleType type_configured = MdmModuleType .fromString(gitmodulesCfg.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle, MdmConfigConstants.Module.MODULE_TYPE.toString())); if (type == null) throw new MdmModuleTypeException("expected module of type " + type + " for repository " + handle + ", but gitmodules file has no known type for this module."); if (type != type_configured) throw new MdmModuleTypeException("expected module of type " + type + " for repository " + handle + ", but gitmodules file states this is a " + type_configured + " module."); // load real path from gitmodule config (probably same as handle, but theoretically allowed to be different) String path = gitmodulesCfg.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle, ConfigConstants.CONFIG_KEY_PATH); this.path = (File.separatorChar != '/') ? path.replace(File.separatorChar, '/') : path; // load remote urls this.urlHistoric = gitmodulesCfg.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle, ConfigConstants.CONFIG_KEY_URL); this.urlLocal = parent.getConfig().getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle, ConfigConstants.CONFIG_KEY_URL); // load indexId the parent expects the submodule to be at (if not already provided) if (indexId != null) this.indexId = indexId; else try { SubmoduleWalk generator = SubmoduleWalk.forIndex(parent).setFilter(PathFilter.create(path)); this.indexId = generator.next() ? generator.getObjectId() : null; } catch (IOException e) { throw new MdmRepositoryIOException(false, parent.getWorkTree().getPath(), e); } // review the submodule and summarize a status. SubmoduleStatusType statusType; if (path == null) // jgit report SubmoduleStatusType.MISSING if no path in .gitmodules file, but I don't even want to deal with that. throw new MdmModuleTypeException("no path for module " + handle + " listed in gitmodules file."); else if (urlLocal == null) // Report uninitialized if no URL in config file statusType = SubmoduleStatusType.UNINITIALIZED; else if (repo == null) // Report uninitialized if no submodule repository statusType = SubmoduleStatusType.UNINITIALIZED; else if (headId == null) // Report uninitialized if no HEAD commit in submodule repository statusType = SubmoduleStatusType.UNINITIALIZED; else if (!headId.equals(indexId)) // Report checked out if HEAD commit is different than index commit statusType = SubmoduleStatusType.REV_CHECKED_OUT; else // Report initialized if HEAD commit is the same as the index commit statusType = SubmoduleStatusType.INITIALIZED; this.status = new SubmoduleStatus(statusType, path, indexId, headId); } else { this.path = handle; this.indexId = null; this.urlHistoric = null; this.urlLocal = null; this.status = null; } }
From source file:net.polydawn.mdm.Plumbing.java
License:Open Source License
public static boolean fetch(Repository repo, MdmModuleDependency module) throws ConfigInvalidException, MdmRepositoryIOException, MdmRepositoryStateException, MdmException, IOException { switch (module.getStatus().getType()) { case MISSING: throw new MajorBug(); case UNINITIALIZED: if (module.getRepo() == null) try { RepositoryBuilder builder = new RepositoryBuilder(); builder.setWorkTree(new File(repo.getWorkTree() + "/" + module.getPath())); builder.setGitDir(new File(repo.getDirectory() + "/modules/" + module.getPath())); module.repo = builder.build(); // we actually *might* not have to make the repo from zero. // this getRepo gets its effective data from SubmoduleWalk.getSubmoduleRepository... // which does its job by looking in the working tree of the parent repo. // meaning if it finds nothing, it certainly won't find any gitdir indirections. // so, even if this is null, we might well have a gitdir cached that we still have to go find. final FileBasedConfig cfg = (FileBasedConfig) module.repo.getConfig(); if (!cfg.getFile().exists()) { // though seemly messy, this is the same question the jgit create() function asks, and it's not exposed to us, so. module.repo.create(false); } else { // do something crazy, because... i think the user's expectation after blowing away their submodule working tree is likely wanting a clean state of index and such here try { new Git(module.getRepo()).reset().setMode(ResetType.HARD).call(); } catch (CheckoutConflictException e) { /* Can a hard reset even have a conflict? */ throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); }//from w w w .j a v a 2 s. c o m } // set up a working tree which points to the gitdir in the parent repo: // handling paths in java, god forbid relative paths, is such an unbelievable backwater. someday please make a whole library that actually disambiguates pathnames from filedescriptors properly int ups = StringUtils.countMatches(module.getPath(), "/"); // look up the path between the `repo` and its possible git dir location. if the gitdir is relocated, we have adjust our own relocations to compensate. String parentGitPointerStr = ".git/"; String parentWorktreePointerStr = "../"; // load it ourselves because we explicitly want the unresolved path, not what jgit would give us back from `repo.getDirectory().toString()`. File parentGitPointer = new File(repo.getWorkTree(), ".git"); if (parentGitPointer.isFile()) { // this shouldn't have to be recursive fortunately (that recursion is done implicitly by the chaining of each guy at each stage). // this does however feel fairly fragile. it's considerable that perhaps we should try to heuristically determine when paths are just to crazy to deal with. but, on the off chance that check was overzealous, it would be very irritating, so let's not. // frankly, if you're doing deeply nested submodules, or other advanced gitdir relocations, at some point you're taking it upon yourself to deal with the inevitably complex outcomes and edge case limitations. parentGitPointerStr = IOForge.readFileAsString(parentGitPointer); if (!"gitdir:".equals(parentGitPointerStr.substring(0, 7))) throw new ConfigInvalidException( "cannot understand location of parent project git directory"); parentGitPointerStr = parentGitPointerStr.substring(7).trim() + "/"; parentWorktreePointerStr = repo.getConfig().getString("core", null, "worktree") + "/"; } // jgit does not appear to create the .git file correctly here :/ // nor even consider it to be jgit's job to create the worktree yet, apparently, so do that module.repo.getWorkTree().mkdirs(); // need modules/[module]/config to contain 'core.worktree' = appropriate String submoduleWorkTreeRelativeToGitDir = StringUtils.repeat("../", ups + 2) + parentWorktreePointerStr + module.getPath(); StoredConfig cnf = module.repo.getConfig(); cnf.setString("core", null, "worktree", submoduleWorkTreeRelativeToGitDir); cnf.save(); // need [module]/.git to contain 'gitdir: appropriate' (which appears to not be normal gitconfig) String submoduleGitDirRelativeToWorkTree = StringUtils.repeat("../", ups + 1) + parentGitPointerStr + "modules/" + module.getPath(); IOForge.saveFile("gitdir: " + submoduleGitDirRelativeToWorkTree + "\n", new File(module.repo.getWorkTree(), ".git")); } catch (IOException e) { throw new MdmRepositoryIOException("create a new submodule", true, module.getHandle(), e); } try { if (initLocalConfig(repo, module)) repo.getConfig().save(); } catch (IOException e) { throw new MdmRepositoryIOException("save changes", true, "the local git configuration file", e); } try { setMdmRemote(module); module.getRepo().getConfig().save(); } catch (IOException e) { throw new MdmRepositoryIOException("save changes", true, "the git configuration file for submodule " + module.getHandle(), e); } case INITIALIZED: if (module.getVersionName() == null || module.getVersionName().equals(module.getVersionActual())) return false; case REV_CHECKED_OUT: try { if (initModuleConfig(repo, module)) module.getRepo().getConfig().save(); } catch (IOException e) { throw new MdmRepositoryIOException("save changes", true, "the git configuration file for submodule " + module.getHandle(), e); } final String versionBranchName = "refs/heads/mdm/release/" + module.getVersionName(); final String versionTagName = "refs/tags/release/" + module.getVersionName(); /* Fetch only the branch labelled with the version requested. */ if (module.getRepo().getRef(versionBranchName) == null) try { RefSpec releaseBranchRef = new RefSpec().setForceUpdate(true).setSource(versionBranchName) .setDestination(versionBranchName); RefSpec releaseTagRef = new RefSpec().setForceUpdate(true).setSource(versionTagName) .setDestination(versionTagName); new Git(module.getRepo()).fetch().setRemote("origin") .setRefSpecs(releaseBranchRef, releaseTagRef).setTagOpt(TagOpt.NO_TAGS).call(); } catch (InvalidRemoteException e) { throw new MdmRepositoryStateException( "find a valid remote origin in the config for the submodule", module.getHandle(), e); } catch (TransportException e) { URIish remote = null; try { //XXX: if we went through all the work to resolve the remote like the fetch command does, we could just as well do it and hand the resolved uri to fetch for better consistency. remote = new RemoteConfig(module.getRepo().getConfig(), "origin").getURIs().get(0); } catch (URISyntaxException e1) { } throw new MdmRepositoryIOException("fetch from a remote", false, remote.toASCIIString(), e) .setAdditionalMessage("check your connectivity and try again?"); } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } /* Drop the files into the working tree. */ try { new Git(module.getRepo()).checkout().setName(versionBranchName).setForce(true).call(); } catch (RefAlreadyExistsException e) { /* I'm not creating a new branch, so this exception wouldn't even make sense. */ throw new MajorBug(e); } catch (RefNotFoundException e) { /* I just got this branch, so we shouldn't have a problem here. */ throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (InvalidRefNameException e) { /* I just got this branch, so we shouldn't have a problem here. */ throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (CheckoutConflictException e) { // this one is just a perfectly reasonable message with a list of files in conflict; we'll take it. throw new MdmRepositoryStateException(module.getHandle(), e); // this currently gets translated to a :'( exception and it's probably more like a :( } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } return true; default: throw new MajorBug(); } }
From source file:net.polydawn.mdm.Plumbing.java
License:Open Source License
/** * Similar to calling `git submodule init [module]`. Also updates the MdmModule cache of values. * @return true if repo.getConfig() has been modified and should be saved. *///from w ww . j ava 2 s . c o m public static boolean initLocalConfig(Repository repo, MdmModule module) { // Ignore entry if URL is already present in config file if (module.getUrlLocal() != null) return false; // Copy 'url' and 'update' fields to local repo config module.urlLocal = module.getUrlHistoric(); repo.getConfig().setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, module.getHandle(), ConfigConstants.CONFIG_KEY_URL, module.getUrlLocal()); repo.getConfig().setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, module.getHandle(), ConfigConstants.CONFIG_KEY_UPDATE, "none"); return true; }
From source file:org.apache.stratos.cartridge.agent.artifact.deployment.synchronizer.git.impl.GitBasedArtifactRepository.java
License:Apache License
public static boolean addRemote(Repository repository, String remoteUrl) { boolean remoteAdded = false; StoredConfig config = repository.getConfig(); config.setString(GitDeploymentSynchronizerConstants.REMOTE, GitDeploymentSynchronizerConstants.ORIGIN, GitDeploymentSynchronizerConstants.URL, remoteUrl); config.setString(GitDeploymentSynchronizerConstants.REMOTE, GitDeploymentSynchronizerConstants.ORIGIN, GitDeploymentSynchronizerConstants.FETCH, GitDeploymentSynchronizerConstants.FETCH_LOCATION); config.setString(GitDeploymentSynchronizerConstants.BRANCH, GitDeploymentSynchronizerConstants.MASTER, GitDeploymentSynchronizerConstants.REMOTE, GitDeploymentSynchronizerConstants.ORIGIN); config.setString(GitDeploymentSynchronizerConstants.BRANCH, GitDeploymentSynchronizerConstants.MASTER, GitDeploymentSynchronizerConstants.MERGE, GitDeploymentSynchronizerConstants.GIT_REFS_HEADS_MASTER); try {// w w w. ja v a 2s . co m config.save(); remoteAdded = true; } catch (IOException e) { log.error( "Error in adding remote origin " + remoteUrl + " for local repository " + repository.toString(), e); } return remoteAdded; }
From source file:org.apache.usergrid.chop.plugin.Utils.java
License:Apache License
/** * @param gitConfigFolder e.g. /your/project/root/.git * * @return Returns git config remote.origin.url field of the repository located at gitConfigFolder *//*from ww w . j a v a 2 s.c om*/ 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); } }
From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java
License:Open Source License
private boolean checkIfWorkAreaAddedAsRemote(Repository repository) { boolean exists = false; try {/*from www . ja va2 s . c o m*/ Config storedConfig = repository.getConfig(); Set<String> remotes = storedConfig.getSubsections("remote"); for (String remoteName : remotes) { logger.debug("Remote: " + remoteName); if (remoteName.equals("work-area")) { exists = true; break; } } } catch (Exception err) { logger.error("Error while reading remotes info.", err); } return exists; }
From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryHelper.java
License:Open Source License
public Repository createGitRepository(Path path) { Repository toReturn; path = Paths.get(path.toAbsolutePath().toString(), GIT_ROOT); try {// w w w .j av a2 s . com toReturn = FileRepositoryBuilder.create(path.toFile()); toReturn.create(); // Get git configuration StoredConfig config = toReturn.getConfig(); // Set compression level (core.compression) config.setInt(CONFIG_SECTION_CORE, null, CONFIG_PARAMETER_COMPRESSION, CONFIG_PARAMETER_COMPRESSION_DEFAULT); // Set big file threshold (core.bigFileThreshold) config.setString(CONFIG_SECTION_CORE, null, CONFIG_PARAMETER_BIG_FILE_THRESHOLD, CONFIG_PARAMETER_BIG_FILE_THRESHOLD_DEFAULT); // Save configuration changes config.save(); } catch (IOException e) { logger.error("Error while creating repository for site with path" + path.toString(), e); toReturn = null; } return toReturn; }