List of usage examples for org.eclipse.jgit.api Git add
public AddCommand add()
From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.AgentVcsSupportTest.java
License:Apache License
@TestFor(issues = "TW-20165") public void push_with_local_mirrors_should_go_to_original_repository() throws Exception { AgentRunningBuild build = createRunningBuild(true); myVcsSupport.updateSources(myRoot, CheckoutRules.DEFAULT, GitUtils.makeVersion("465ad9f630e451b9f2b782ffb09804c6a98c4bb9", 1289483394000L), myCheckoutDir, build, false);//from w w w . ja va 2 s . c om final File fileToChange = new File(myCheckoutDir, "file"); FileUtil.writeToFile(fileToChange, "text".getBytes()); Repository r = new RepositoryBuilder().setWorkTree(myCheckoutDir).build(); Git git = new Git(r); git.add().addFilepattern("file").call(); RevCommit commitDuringTheBuild = git.commit().setMessage("Commit during the build").call(); new PushCommand().run(getGitPath(), myCheckoutDir.getAbsolutePath());//push using native git, seems like jgit doesn't respect url.insteadOf settings Repository remote = new RepositoryBuilder().setGitDir(myMainRepo).build(); assertTrue("Push didn't go to the remote repository", remote.hasObject(commitDuringTheBuild)); }
From source file:licenseUtil.Utils.java
License:Apache License
public static void addToRepository(String gitDir, String newFN) { try {/*w w w . j ava 2s . com*/ // Open an existing repository Repository existingRepo = new FileRepositoryBuilder().setGitDir(new File(gitDir + "/.git")).build(); Git git = new Git(existingRepo); File newFile = new File(gitDir + File.separator + newFN); newFile.createNewFile(); git.add().addFilepattern(newFile.getName()).call(); } catch (GitAPIException e) { logger.warn("Could not the file \"" + newFN + "\" to local repository: \"" + gitDir + "."); } catch (IOException e) { logger.warn("Could not open local git repository directory: \"" + gitDir + "\""); } }
From source file:net.orpiske.ssps.common.scm.git.GitSCM.java
License:Apache License
public void add(final File file) throws FileAddException, ScmAccessException { Repository repository = accessRepository(file); Git git = new Git(repository); AddCommand pullCommand = git.add(); try {/*from w w w . j av a 2 s . co m*/ pullCommand.addFilepattern(file.getName()).call(); } catch (NoFilepatternException e1) { throw new FileAddException("Unable to add file or directory: " + e1.getMessage(), e1); } catch (GitAPIException e1) { throw new FileAddException("Unable to add file or directory: " + e1.getMessage(), e1); } }
From source file:org.abratuhi.camel.GitLogComponentTest.java
License:Apache License
public void setUp() throws Exception { repodir = File.createTempFile("tmp", "repo"); repodir.delete();/*from www.java 2 s .c om*/ repodir.mkdir(); repogit = new File(repodir, ".git"); final FileRepository repo = new FileRepository(repogit); Git git = new Git(repo); repo.create(); final File repofile = File.createTempFile("tmp", "repofile", repodir); git.add().addFilepattern(".").call(); git.commit().setMessage("Test message").call(); super.setUp(); }
From source file:org.apache.gobblin.service.modules.flow.MultiHopFlowCompilerTest.java
License:Apache License
@Test(dependsOnMethods = "testMulticastPath") public void testGitFlowGraphMonitorService() throws IOException, GitAPIException, URISyntaxException, InterruptedException { File remoteDir = new File(TESTDIR + "/remote"); File cloneDir = new File(TESTDIR + "/clone"); File flowGraphDir = new File(cloneDir, "/gobblin-flowgraph"); //Clean up/*from w w w . ja v a2s . c o m*/ cleanUpDir(TESTDIR); // Create a bare repository RepositoryCache.FileKey fileKey = RepositoryCache.FileKey.exact(remoteDir, FS.DETECTED); Repository remoteRepo = fileKey.open(false); remoteRepo.create(true); Git gitForPush = Git.cloneRepository().setURI(remoteRepo.getDirectory().getAbsolutePath()) .setDirectory(cloneDir).call(); // push an empty commit as a base for detecting changes gitForPush.commit().setMessage("First commit").call(); RefSpec masterRefSpec = new RefSpec("master"); gitForPush.push().setRemote("origin").setRefSpecs(masterRefSpec).call(); URI flowTemplateCatalogUri = this.getClass().getClassLoader().getResource("template_catalog").toURI(); Config config = ConfigBuilder.create() .addPrimitive( GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_REPO_URI, remoteRepo.getDirectory().getAbsolutePath()) .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_REPO_DIR, TESTDIR + "/git-flowgraph") .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "." + ConfigurationKeys.GIT_MONITOR_POLLING_INTERVAL, 5) .addPrimitive(ServiceConfigKeys.TEMPLATE_CATALOGS_FULLY_QUALIFIED_PATH_KEY, flowTemplateCatalogUri.toString()) .build(); //Create a MultiHopFlowCompiler instance specCompiler = new MultiHopFlowCompiler(config, Optional.absent(), false); specCompiler.setActive(true); //Ensure node1 is not present in the graph Assert.assertNull(specCompiler.getFlowGraph().getNode("node1")); // push a new node file File nodeDir = new File(flowGraphDir, "node1"); File nodeFile = new File(nodeDir, "node1.properties"); nodeDir.mkdirs(); nodeFile.createNewFile(); Files.write(FlowGraphConfigurationKeys.DATA_NODE_IS_ACTIVE_KEY + "=true\nparam1=val1" + "\n", nodeFile, Charsets.UTF_8); // add, commit, push node gitForPush.add().addFilepattern(formNodeFilePath(flowGraphDir, nodeDir.getName(), nodeFile.getName())) .call(); gitForPush.commit().setMessage("Node commit").call(); gitForPush.push().setRemote("origin").setRefSpecs(masterRefSpec).call(); // polling is every 5 seconds, so wait twice as long and check TimeUnit.SECONDS.sleep(10); //Test that a DataNode is added to FlowGraph DataNode dataNode = specCompiler.getFlowGraph().getNode("node1"); Assert.assertEquals(dataNode.getId(), "node1"); Assert.assertEquals(dataNode.getRawConfig().getString("param1"), "val1"); }
From source file:org.apache.maven.scm.provider.git.jgit.command.checkin.JGitCheckInCommand.java
License:Apache License
/** * {@inheritDoc}/* w ww.j a v a2 s. c o m*/ */ protected CheckInScmResult executeCheckInCommand(ScmProviderRepository repo, ScmFileSet fileSet, String message, ScmVersion version) throws ScmException { Git git = null; try { File basedir = fileSet.getBasedir(); git = Git.open(basedir); boolean doCommit = false; if (!fileSet.getFileList().isEmpty()) { doCommit = JGitUtils.addAllFiles(git, fileSet).size() > 0; } else { // add all tracked files which are modified manually Set<String> changeds = git.status().call().getModified(); if (changeds.isEmpty()) { // warn there is nothing to add getLogger().warn("there are no files to be added"); doCommit = false; } else { AddCommand add = git.add(); for (String changed : changeds) { getLogger().debug("add manualy: " + changed); add.addFilepattern(changed); doCommit = true; } add.call(); } } List<ScmFile> checkedInFiles = Collections.emptyList(); if (doCommit) { UserInfo author = getAuthor(repo, git); UserInfo committer = getCommitter(repo, git); CommitCommand command = git.commit().setMessage(message).setAuthor(author.name, author.email); command.setCommitter(committer.name, committer.email); RevCommit commitRev = command.call(); getLogger().info("commit done: " + commitRev.getShortMessage()); checkedInFiles = JGitUtils.getFilesInCommit(git.getRepository(), commitRev); if (getLogger().isDebugEnabled()) { for (ScmFile scmFile : checkedInFiles) { getLogger().debug("in commit: " + scmFile); } } } if (repo.isPushChanges()) { String branch = version != null ? version.getName() : null; if (StringUtils.isBlank(branch)) { branch = git.getRepository().getBranch(); } RefSpec refSpec = new RefSpec(Constants.R_HEADS + branch + ":" + Constants.R_HEADS + branch); getLogger().info("push changes to remote... " + refSpec.toString()); JGitUtils.push(getLogger(), git, (GitScmProviderRepository) repo, refSpec); } return new CheckInScmResult("JGit checkin", checkedInFiles); } catch (Exception e) { throw new ScmException("JGit checkin failure!", e); } finally { JGitUtils.closeRepo(git); } }
From source file:org.apache.maven.scm.provider.git.jgit.command.JGitUtils.java
License:Apache License
/** * Adds all files in the given fileSet to the repository. * * @param git the repo to add the files to * @param fileSet the set of files within the workspace, the files are added * relative to the basedir of this fileset * @return a list of added files/*w ww. j av a 2s .com*/ * @throws GitAPIException * @throws NoFilepatternException */ public static List<ScmFile> addAllFiles(Git git, ScmFileSet fileSet) throws GitAPIException, NoFilepatternException { URI baseUri = fileSet.getBasedir().toURI(); AddCommand add = git.add(); for (File file : fileSet.getFileList()) { if (!file.isAbsolute()) { file = new File(fileSet.getBasedir().getPath(), file.getPath()); } if (file.exists()) { String path = relativize(baseUri, file); add.addFilepattern(path); add.addFilepattern(file.getAbsolutePath()); } } add.call(); Status status = git.status().call(); Set<String> allInIndex = new HashSet<String>(); allInIndex.addAll(status.getAdded()); allInIndex.addAll(status.getChanged()); // System.out.println("All in index: "+allInIndex.size()); List<ScmFile> addedFiles = new ArrayList<ScmFile>(allInIndex.size()); // rewrite all detected files to now have status 'checked_in' for (String entry : allInIndex) { ScmFile scmfile = new ScmFile(entry, ScmFileStatus.ADDED); // if a specific fileSet is given, we have to check if the file is // really tracked for (Iterator<File> itfl = fileSet.getFileList().iterator(); itfl.hasNext();) { String path = FilenameUtils.normalizeFilename(relativize(baseUri, itfl.next())); if (path.equals(FilenameUtils.normalizeFilename(scmfile.getPath()))) { addedFiles.add(scmfile); } } } return addedFiles; }
From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java
License:Apache License
protected void pushChanges(final File target) { try {//from w w w . j a v a 2 s. c om // // Grab our working repository // Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath(); final Git git = Git.open(repoPath.toFile()); // // Get our status // final String base; Status status; if (target == null) { base = "."; } else { Path relativePath = repoPath.relativize(Paths.get(target.getPath())); base = relativePath.toString(); } if (logger.isDebugEnabled()) { logger.debug("Status on base: " + base); } status = git.status().addPath(base).call(); // // Check if its clean // if (status.isClean()) { // // Its clean // AdminNotification.warn(target.getName() + " is clean!"); return; } // // Create the window // final GitPushWindow window = new GitPushWindow(git, target, status); window.setCaption("Push Changes"); window.setModal(true); window.addCloseListener(new CloseListener() { private static final long serialVersionUID = 1L; @Override public void windowClose(CloseEvent e) { if (window.isSaved() == false) { return; } try { // // Needs to be added first // DirCache cache = git.add().addFilepattern(base).call(); for (int i = 0; i < cache.getEntryCount(); i++) { DirCacheEntry entry = cache.getEntry(i); if (logger.isDebugEnabled()) { logger.debug("Entry: " + entry); } } // // Next they need to be committed // RevCommit rev = git.commit().setMessage(window.getComment()).call(); if (logger.isDebugEnabled()) { logger.debug("RevCommit: " + rev); } // // Now we can push changes to the Git repository // Iterable<PushResult> results = git.push().call(); for (PushResult result : results) { logger.info(result); } // // Have the container fire an item set change notification // self.treeContainer.updateItem(target); } catch (NoWorkTreeException | GitAPIException e1) { logger.error(e); AdminNotification.error("Exception occurred while trying to push: " + e1); } } }); window.center(); UI.getCurrent().addWindow(window); } catch (IOException | GitAPIException e) { logger.error(e); AdminNotification.error("Exception occurred while trying to get status: " + e); } }
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 {//from ww w. ja v a 2 s. 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.sshd.git.pack.GitPackCommandTest.java
License:Apache License
@Test public void testGitPack() throws Exception { Assume.assumeFalse("On windows this activates TortoisePlink", OsUtils.isWin32()); Path targetParent = detectTargetFolder().getParent(); Path gitRootDir = getTempTargetRelativeFile(getClass().getSimpleName()); try (SshServer sshd = setupTestServer()) { Path serverRootDir = gitRootDir.resolve("server"); sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory())); sshd.setCommandFactory(/* ww w . ja va 2 s . co m*/ new GitPackCommandFactory(Utils.resolveRelativeRemotePath(targetParent, serverRootDir))); sshd.start(); int port = sshd.getPort(); try { Path serverDir = serverRootDir.resolve("test.git"); Utils.deleteRecursive(serverDir); Git.init().setBare(true).setDirectory(serverDir.toFile()).call(); JSch.setConfig("StrictHostKeyChecking", "no"); CredentialsProvider.setDefault( new UsernamePasswordCredentialsProvider(getCurrentTestName(), getCurrentTestName())); SshSessionFactory.setInstance(new GitSshdSessionFactory()); Path localRootDir = gitRootDir.resolve("local"); Path localDir = localRootDir.resolve(serverDir.getFileName()); Utils.deleteRecursive(localDir); Git.cloneRepository().setURI("ssh://" + getCurrentTestName() + "@" + TEST_LOCALHOST + ":" + port + "/" + serverDir.getFileName()).setDirectory(localDir.toFile()).call(); Git git = Git.open(localDir.toFile()); git.commit().setMessage("First Commit").setCommitter(getCurrentTestName(), "sshd@apache.org") .call(); git.push().call(); Path readmeFile = Files.createFile(localDir.resolve("readme.txt")); git.add().addFilepattern(readmeFile.getFileName().toString()).call(); git.commit().setMessage(getCurrentTestName()).setCommitter(getCurrentTestName(), "sshd@apache.org") .call(); git.push().call(); git.pull().setRebase(true).call(); } finally { sshd.stop(); } } }