List of usage examples for org.eclipse.jgit.lib StoredConfig save
public abstract void save() throws IOException;
From source file:net.polydawn.mdm.commands.MdmAlterCommand.java
License:Open Source License
public MdmExitMessage call() throws ConfigInvalidException, IOException, MdmException { try {/*from w w w . j a va 2 s . c o m*/ assertInRepoRoot(); } catch (MdmExitMessage e) { return e; } // touch up args a tad. tab completion in the terminal tends to suggest *almost* what you want, but with a trailing slash because it's a directory, and git doesn't like that slash. so, we'll sand down that sharp corner a bit. String name = args.getString("name"); if (name.endsWith("/")) name = name.substring(0, name.length() - 1); // load current module state StoredConfig gitmodulesCfg = new FileBasedConfig(new File(repo.getWorkTree(), Constants.DOT_GIT_MODULES), repo.getFS()); try { gitmodulesCfg.load(); } catch (ConfigInvalidException e) { throw new MdmExitInvalidConfig(Constants.DOT_GIT_MODULES); } MdmModuleDependency module; try { module = MdmModuleDependency.load(repo, name, gitmodulesCfg); } catch (MdmModuleTypeException e) { return new MdmExitMessage(":(", "there is no mdm dependency by that name."); } // give a look at the remote path and see what versions are physically available. List<String> versions; try { //XXX: here the triplicate-and-then-some configuration is a tanglefuck again. do we use the origin, or the url in the submodule config, or the url that's initialized in the parent .git/config, or the url in the .gitmodules file, or some complicated fallback pattern that covers all of them, or initialize the ones that aren't yet, or...?? Original mdm took the value from .gitmodules, which is the least likely to be uninitialized, but also not the most correct. if (module.getRepo() == null) versions = Plumbing.getVersionManifest(repo, module.getUrlHistoric()); else versions = Plumbing.getVersionManifest(module.getRepo(), "origin"); } catch (InvalidRemoteException e) { return new MdmExitMessage(":(", "the submodule remote origin url isn't initialized. maybe run `mdm update` first so there's something in place before we alter?"); } catch (TransportException e) { return new MdmExitMessage(":'(", "transport failed! check that the submodule remote origin url is correct and reachable and try again?\n (error message: " + e.getMessage() + ")"); } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } if (versions.size() == 0) return new MdmExitMessage(":(", "no releases could be found at the submodule remote origin url -- it doesn't look like releases that mdm understands are there.\ncheck the origin url in the submodule's config. if this url worked in the past, maybe the project maintainers moved their releases repo?"); // if a specific version name was given, we'll just go straight at it; otherwise we present options interactively from the manifest of versions the remote reported. String version; if (args.getString("version") != null) { version = args.getString("version"); if (!versions.contains(version)) return new MdmExitMessage(":(", "no version labelled " + version + " available from the provided remote url."); } else { version = Loco.promptForVersion(os, versions); } // if you specify the version you already had, okay, we'll just put our tools down. if (module.getVersionName().equals(version)) return new MdmExitMessage(":I", "that version is already specified! no changes made."); // do the submodule/dependency dancing gitmodulesCfg.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, module.getHandle(), MdmConfigConstants.Module.DEPENDENCY_VERSION.toString(), version); module = MdmModuleDependency.load(repo, module.getPath(), gitmodulesCfg); // reload the MdmModule completely because it's not yet implmented intelligently enough to be able to refresh a bunch of its cached state Plumbing.fetch(repo, module); gitmodulesCfg.save(); // don't do this save until after the fetch: if the fetch blows up, it's better that we don't have this mutated, because that leaves you with slightly stranger output from your next `mdm status` query. // commit the changes try { new Git(repo).add().addFilepattern(module.getPath()).addFilepattern(Constants.DOT_GIT_MODULES).call(); } catch (NoFilepatternException e) { throw new MajorBug(e); // why would an api throw exceptions like this *checked*? } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } try { new Git(repo).commit().setOnly(module.getPath()).setOnly(Constants.DOT_GIT_MODULES) .setMessage("shifting dependency on " + name + " to version " + version + ".").call(); } catch (NoHeadException e) { throw new MdmException("your repository is in an invalid state!", e); } catch (NoMessageException e) { throw new MajorBug(e); // why would an api throw exceptions like this *checked*? } catch (UnmergedPathsException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (ConcurrentRefUpdateException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (WrongRepositoryStateException e) { 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); } return new MdmExitMessage(":D", "altered dependency on " + name + " to version " + version + " successfully!"); }
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/*from w w w .j a v a2 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.MdmRemoveCommand.java
License:Open Source License
public MdmExitMessage call() throws IOException, MdmException { try {/*from w ww .j a v a 2 s. c om*/ assertInRepoRoot(); } catch (MdmExitMessage e) { return e; } // touch up args a tad. tab completion in the terminal tends to suggest *almost* what you want, but with a trailing slash because it's a directory, and git doesn't like that slash. so, we'll sand down that sharp corner a bit. String name = args.getString("name"); if (name.endsWith("/")) name = name.substring(0, name.length() - 1); // load up config StoredConfig gitmodulesCfg = new FileBasedConfig(new File(repo.getWorkTree(), Constants.DOT_GIT_MODULES), repo.getFS()); try { gitmodulesCfg.load(); } catch (ConfigInvalidException e) { throw new MdmExitInvalidConfig(Constants.DOT_GIT_MODULES); } // if there's no module there, we haven't got much to do try { MdmModuleDependency.load(repo, name, gitmodulesCfg); } catch (MdmModuleTypeException _) { return new MdmExitMessage(":I", "there is no mdm dependency by that name."); } // stage the remove and blow away the repo dirs try { new Git(repo).rm().setCached(true).addFilepattern(name).call(); } catch (NoFilepatternException e) { throw new MajorBug(e); // why would an api throw exceptions like this *checked*? } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } IOForge.delete(new File(repo.getWorkTree(), name)); IOForge.delete(new File(repo.getDirectory(), "modules/" + name)); // if this is one of the newer version of git (specifically, 1.7.8 or newer) that stores the submodule's data in the parent projects .git dir, clear that out forcefully as well. // blow away gitmodule config section gitmodulesCfg.unsetSection(ConfigConstants.CONFIG_SUBMODULE_SECTION, name); gitmodulesCfg.save(); // commit the changes try { new Git(repo).add().addFilepattern(name).addFilepattern(Constants.DOT_GIT_MODULES).call(); } catch (NoFilepatternException e) { throw new MajorBug(e); // why would an api throw exceptions like this *checked*? } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } try { new Git(repo).commit().setOnly(name).setOnly(Constants.DOT_GIT_MODULES) .setMessage("removing dependency on " + name + ".").call(); } catch (NoHeadException e) { throw new MdmException("your repository is in an invalid state!", e); } catch (NoMessageException e) { throw new MajorBug(e); // why would an api throw exceptions like this *checked*? } catch (UnmergedPathsException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (ConcurrentRefUpdateException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (WrongRepositoryStateException e) { 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); } // clear out local git config StoredConfig localConfig = repo.getConfig(); localConfig.unsetSection(ConfigConstants.CONFIG_SUBMODULE_SECTION, name); localConfig.save(); return new MdmExitMessage(":D", "removed dependency on " + name + "!"); }
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 ww w . j a v a2 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:org.apache.maven.scm.provider.git.jgit.command.checkin.JGitCheckInCommandCommitterAuthorTckTest.java
License:Apache License
@Override public void testCheckInCommandTest() throws Exception { File fooJava = new File(getWorkingCopy(), "src/main/java/Foo.java"); assertFalse("check Foo.java doesn't yet exist", fooJava.canRead()); Git git = Git.open(getWorkingCopy()); RevCommit head = getHeadCommit(git.getRepository()); // Mark created the test repo... assertEquals("Mark Struberg", head.getCommitterIdent().getName()); JGitUtils.closeRepo(git);/* w ww. j a va 2s . c o m*/ createAndCommitFile(fooJava, null); // change user in config git = Git.open(getWorkingCopy()); StoredConfig config = git.getRepository().getConfig(); unsetConfig(config); config.setString("user", null, "name", "Dominik"); config.setString("user", null, "email", "domi@mycomp.com"); config.save(); // make a commit createAndCommitFile(fooJava, null); // check new commit is done with new user in config head = getHeadCommit(git.getRepository()); assertEquals("Dominik", head.getCommitterIdent().getName()); assertEquals("Dominik", head.getAuthorIdent().getName()); assertEquals("domi@mycomp.com", head.getAuthorIdent().getEmailAddress()); assertEquals("domi@mycomp.com", head.getCommitterIdent().getEmailAddress()); JGitUtils.closeRepo(git); // change user in config git = Git.open(getWorkingCopy()); config = git.getRepository().getConfig(); unsetConfig(config); config.setString("user", null, "name", "dbartholdi"); config.save(); // make a change createAndCommitFile(fooJava, null); // check new commit is done with new user in config head = getHeadCommit(git.getRepository()); assertEquals("dbartholdi", head.getCommitterIdent().getName()); assertFalse("no mail domain is configured, git system default should be used", head.getCommitterIdent().getEmailAddress().contains("dbartholdi")); JGitUtils.closeRepo(git); // unset a user and maven user but set default mail domain git = Git.open(getWorkingCopy()); config = git.getRepository().getConfig(); unsetConfig(config); config.setString(JGitCheckInCommand.GIT_MAVEN_SECTION, null, JGitCheckInCommand.GIT_MAILDOMAIN, "comp.com"); config.save(); // make a change with an user on the commandline createAndCommitFile(fooJava, "dude"); // check new commit is done with new maven user in config head = getHeadCommit(git.getRepository()); assertEquals("dude", head.getCommitterIdent().getName()); assertEquals("dude@comp.com", head.getCommitterIdent().getEmailAddress()); assertEquals("dude", head.getAuthorIdent().getName()); assertEquals("dude@comp.com", head.getAuthorIdent().getEmailAddress()); JGitUtils.closeRepo(git); // unset a user and maven user but set default mail domain git = Git.open(getWorkingCopy()); config = git.getRepository().getConfig(); unsetConfig(config); config.setString("user", null, "name", "dbartholdi"); config.setBoolean(JGitCheckInCommand.GIT_MAVEN_SECTION, null, JGitCheckInCommand.GIT_FORCE, true); config.setString(JGitCheckInCommand.GIT_MAVEN_SECTION, null, JGitCheckInCommand.GIT_MAILDOMAIN, "anycomp.com"); config.save(); // make a change with an user on the commandline createAndCommitFile(fooJava, "dude"); // check new commit is done with new maven user in config head = getHeadCommit(git.getRepository()); assertEquals("dude", head.getCommitterIdent().getName()); assertEquals("dude@anycomp.com", head.getCommitterIdent().getEmailAddress()); assertEquals("dude", head.getAuthorIdent().getName()); assertEquals("dude@anycomp.com", head.getAuthorIdent().getEmailAddress()); JGitUtils.closeRepo(git); // unset a user and maven user but set default mail domain git = Git.open(getWorkingCopy()); config = git.getRepository().getConfig(); unsetConfig(config); config.setString(JGitCheckInCommand.GIT_MAVEN_SECTION, null, JGitCheckInCommand.GIT_MAILDOMAIN, "anycomp.com"); config.save(); // make a change with no username given createAndCommitFile(fooJava, null); // check new commit does not contain the configured email domain head = getHeadCommit(git.getRepository()); assertFalse(head.getCommitterIdent().getEmailAddress().contains("anycomp.com")); assertFalse(head.getAuthorIdent().getEmailAddress().contains("anycomp.com")); JGitUtils.closeRepo(git); // unset a user and full maven section git = Git.open(getWorkingCopy()); config = git.getRepository().getConfig(); unsetConfig(config); config.save(); // make a change with an user on the commandline createAndCommitFile(fooJava, "dundy"); // check new commit is done with new maven user in config head = getHeadCommit(git.getRepository()); assertEquals("dundy", head.getCommitterIdent().getName()); assertEquals("dundy", head.getAuthorIdent().getName()); assertTrue( "the maven user (from parameter) name must be in the committer mail when nothing else is configured", head.getCommitterIdent().getEmailAddress().contains("dundy")); assertTrue("the user name (from parameter) must be in the author mail when nothing else is configured", head.getAuthorIdent().getEmailAddress().contains("dundy")); JGitUtils.closeRepo(git); // unset all configs git = Git.open(getWorkingCopy()); config = git.getRepository().getConfig(); unsetConfig(config); config.save(); // make a change with no user on the commandline createAndCommitFile(fooJava, null); // check new commit is has a committer/author with email set head = getHeadCommit(git.getRepository()); assertNotNull(head.getCommitterIdent().getName()); assertNotNull(head.getAuthorIdent().getName()); assertNotNull(head.getCommitterIdent().getEmailAddress()); assertNotNull(head.getAuthorIdent().getEmailAddress()); JGitUtils.closeRepo(git); }
From source file:org.apache.nifi.registry.provider.flow.git.TestGitFlowPersistenceProvider.java
License:Apache License
private void assertProvider(final Map<String, String> properties, final GitConsumer gitConsumer, final Consumer<GitFlowPersistenceProvider> assertion, boolean deleteDir) throws IOException, GitAPIException { final File gitDir = new File(properties.get(GitFlowPersistenceProvider.FLOW_STORAGE_DIR_PROP)); try {/* w w w.j a va2 s . c o m*/ FileUtils.ensureDirectoryExistAndCanReadAndWrite(gitDir); try (final Git git = Git.init().setDirectory(gitDir).call()) { logger.debug("Initiated a git repository {}", git); final StoredConfig config = git.getRepository().getConfig(); config.setString("user", null, "name", "git-user"); config.setString("user", null, "email", "git-user@example.com"); config.save(); gitConsumer.accept(git); } final GitFlowPersistenceProvider persistenceProvider = new GitFlowPersistenceProvider(); final ProviderConfigurationContext configurationContext = new StandardProviderConfigurationContext( properties); persistenceProvider.onConfigured(configurationContext); assertion.accept(persistenceProvider); } finally { if (deleteDir) { FileUtils.deleteFile(gitDir, true); } } }
From source file:org.apache.openaz.xacml.admin.XacmlAdminUI.java
License:Apache License
private static void initializeGitRepository() throws ServletException { XacmlAdminUI.repositoryPath = Paths .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY)); FileRepositoryBuilder builder = new FileRepositoryBuilder(); try {/* w w w. j a va 2s . c o m*/ XacmlAdminUI.repository = builder.setGitDir(XacmlAdminUI.repositoryPath.toFile()).readEnvironment() .findGitDir().setBare().build(); if (Files.notExists(XacmlAdminUI.repositoryPath) || Files.notExists(Paths.get(XacmlAdminUI.repositoryPath.toString(), "HEAD"))) { // // Create it if it doesn't exist. As a bare repository // logger.info("Creating bare git repository: " + XacmlAdminUI.repositoryPath.toString()); XacmlAdminUI.repository.create(); // // Add the magic file so remote works. // Path daemon = Paths.get(XacmlAdminUI.repositoryPath.toString(), "git-daemon-export-ok"); Files.createFile(daemon); } } catch (IOException e) { logger.error("Failed to build repository: " + repository, e); throw new ServletException(e.getMessage(), e.getCause()); } // // Make sure the workspace directory is created // Path workspace = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_WORKSPACE)); workspace = workspace.toAbsolutePath(); if (Files.notExists(workspace)) { try { Files.createDirectory(workspace); } catch (IOException e) { logger.error("Failed to build workspace: " + workspace, e); throw new ServletException(e.getMessage(), e.getCause()); } } // // Create the user workspace directory // workspace = Paths.get(workspace.toString(), "pe"); if (Files.notExists(workspace)) { try { Files.createDirectory(workspace); } catch (IOException e) { logger.error("Failed to create directory: " + workspace, e); throw new ServletException(e.getMessage(), e.getCause()); } } // // Get the path to where the repository is going to be // Path gitPath = Paths.get(workspace.toString(), XacmlAdminUI.repositoryPath.getFileName().toString()); if (Files.notExists(gitPath)) { try { Files.createDirectory(gitPath); } catch (IOException e) { logger.error("Failed to create directory: " + gitPath, e); throw new ServletException(e.getMessage(), e.getCause()); } } // // Initialize the domain structure // String base = null; String domain = XacmlAdminUI.getDomain(); if (domain != null) { for (String part : Splitter.on(':').trimResults().split(domain)) { if (base == null) { base = part; } Path subdir = Paths.get(gitPath.toString(), part); if (Files.notExists(subdir)) { try { Files.createDirectory(subdir); Files.createFile(Paths.get(subdir.toString(), ".svnignore")); } catch (IOException e) { logger.error("Failed to create: " + subdir, e); throw new ServletException(e.getMessage(), e.getCause()); } } } } else { try { Files.createFile(Paths.get(workspace.toString(), ".svnignore")); base = ".svnignore"; } catch (IOException e) { logger.error("Failed to create file", e); throw new ServletException(e.getMessage(), e.getCause()); } } try { // // These are the sequence of commands that must be done initially to // finish setting up the remote bare repository. // Git git = Git.init().setDirectory(gitPath.toFile()).setBare(false).call(); git.add().addFilepattern(base).call(); git.commit().setMessage("Initialize Bare Repository").call(); StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "origin", "url", XacmlAdminUI.repositoryPath.toAbsolutePath().toString()); config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); config.save(); git.push().setRemote("origin").add("master").call(); /* * This will not work unless git.push().setRemote("origin").add("master").call(); * is called first. Otherwise it throws an exception. However, if the push() is * called then calling this function seems to add nothing. * git.branchCreate().setName("master") .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM) .setStartPoint("origin/master").setForce(true).call(); */ } catch (GitAPIException | IOException e) { logger.error(e); throw new ServletException(e.getMessage(), e.getCause()); } }
From source file:org.apache.openaz.xacml.admin.XacmlAdminUI.java
License:Apache License
/** * Initializes a user's git repository.//from w w w . j a va 2 s . c om * * * @param workspacePath * @param userId * @param email * @return * @throws IOException * @throws InvalidRemoteException * @throws TransportException * @throws GitAPIException */ private static Path initializeUserRepository(Path workspacePath, String userId, URI email) throws IOException, InvalidRemoteException, TransportException, GitAPIException { Path gitPath = null; // // Initialize the User's Git repository // if (Files.notExists(workspacePath)) { logger.info("Creating user workspace: " + workspacePath.toAbsolutePath().toString()); // // Create our user's directory // Files.createDirectory(workspacePath); } gitPath = Paths.get(workspacePath.toString(), XacmlAdminUI.repositoryPath.getFileName().toString()); if (Files.notExists(gitPath)) { // // It doesn't exist yet, so Clone it and check it out // logger.info("Cloning user git directory: " + gitPath.toAbsolutePath().toString()); Git.cloneRepository().setURI(XacmlAdminUI.repositoryPath.toUri().toString()) .setDirectory(gitPath.toFile()).setNoCheckout(false).call(); // // Set userid // Git git = Git.open(gitPath.toFile()); StoredConfig config = git.getRepository().getConfig(); config.setString("user", null, "name", userId); if (email != null && email.getPath() != null) { config.setString("user", null, "email", email.toString()); } config.save(); } return gitPath; }
From source file:org.apache.stratos.cartridge.agent.artifact.deployment.synchronizer.git.impl.GitBasedArtifactRepository.java
License:Apache License
/** * Handles the Invalid configuration issues * * @param gitRepoCtx RepositoryContext instance of the tenant *///from www . j a va2s .c o m private void handleInvalidConfigurationError(RepositoryContext gitRepoCtx) { StoredConfig storedConfig = gitRepoCtx.getLocalRepo().getConfig(); boolean modifiedConfig = false; if (storedConfig != null) { if (storedConfig.getString("branch", "master", "remote") == null || storedConfig.getString("branch", "master", "remote").isEmpty()) { storedConfig.setString("branch", "master", "remote", "origin"); modifiedConfig = true; } if (storedConfig.getString("branch", "master", "merge") == null || storedConfig.getString("branch", "master", "merge").isEmpty()) { storedConfig.setString("branch", "master", "merge", "refs/heads/master"); modifiedConfig = true; } if (modifiedConfig) { try { storedConfig.save(); // storedConfig.load(); } catch (IOException e) { String message = "Error saving git configuration file in local repo at " + gitRepoCtx.getGitLocalRepoPath(); System.out.println(message); log.error(message, e); } } } }
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 {//from www . j a v a 2s. c o m config.save(); remoteAdded = true; } catch (IOException e) { log.error( "Error in adding remote origin " + remoteUrl + " for local repository " + repository.toString(), e); } return remoteAdded; }