@Before public void setUp() throws Exception { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); FileUtils.mkdir(new File(root.getLocation().toFile(), "Sub"), true); gitDir = new File(new File(root.getLocation().toFile(), "Sub"), Constants.DOT_GIT); repository = FileRepositoryBuilder.create(gitDir); repository.create(); project = root.getProject(TEST_PROJECT); project.create(null); project.open(null); IProjectDescription description = project.getDescription(); description.setLocation(root.getLocation().append(TEST_PROJECT_LOC)); project.move(description, IResource.FORCE, null); project2 = root.getProject(TEST_PROJECT2); project2.create(null); project2.open(null); gitDir2 = new File(project2.getLocation().toFile().getAbsoluteFile(), Constants.DOT_GIT); repository2 = FileRepositoryBuilder.create(gitDir2); repository2.create(); RepositoryMapping mapping = RepositoryMapping.create(project, gitDir); RepositoryMapping mapping2 = RepositoryMapping.create(project2, gitDir2); GitProjectData projectData = new GitProjectData(project); GitProjectData projectData2 = new GitProjectData(project2); projectData.setRepositoryMappings(Collections.singletonList(mapping)); projectData.store(); projectData2.setRepositoryMappings(Collections.singletonList(mapping2)); projectData2.store(); GitProjectData.add(project, projectData); GitProjectData.add(project2, projectData2); RepositoryProvider.map(project, GitProvider.class.getName()); RepositoryProvider.map(project2, GitProvider.class.getName()); JGitTestUtil.write( new File(repository.getWorkTree(), TEST_PROJECT + "/" + TEST_FILE), "Some data"); JGitTestUtil.write(new File(repository2.getWorkTree(), TEST_FILE2), "Some other data"); project.refreshLocal(IResource.DEPTH_INFINITE, null); project2.refreshLocal(IResource.DEPTH_INFINITE, null); git = new Git(repository); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git = new Git(repository2); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.branchRename().setNewName("main").call(); }
@Before public void setUp() throws IOException, ConfigInvalidException { MockitoAnnotations.initMocks(this); DfsRepositoryDescription dfsRepositoryDescription = new DfsRepositoryDescription("test"); repository = new UniqueInMemoryRepository(dfsRepositoryDescription); InputStream stream = new FileInputStream(new File("fixtures/repository-config")); StringWriter writer = new StringWriter(); IOUtils.copy(stream, writer); repository.getConfig().fromText(writer.toString()); repository.create(); }
public void init() throws GitException { if (hasGitRepo()) { throw new GitException(".git directory already exists! Has it already been initialised?"); } try { final Repository repo = new FileRepository(new File(workspace.child(Constants.DOT_GIT).getRemote())); repo.create(); } catch (IOException ioe) { throw new GitException("Error initiating git repo.", ioe); } }
/** * Creates a new test repository * * @param gitDir * @throws IOException */ public TestRepository(File gitDir) throws IOException { repository = new FileRepository(gitDir); repository.create(); try { workdirPrefix = repository.getWorkTree().getCanonicalPath(); } catch (IOException err) { workdirPrefix = repository.getWorkTree().getAbsolutePath(); } workdirPrefix = workdirPrefix.replace('\\', '/'); if (!workdirPrefix.endsWith("/")) // $NON-NLS-1$ workdirPrefix += "/"; // $NON-NLS-1$ }
private Repository findBuildPlace(Repository repository) throws IOException { String originalPath = repository.getDirectory().getAbsolutePath(); String targetPath = originalPath.replaceFirst( context.configuration().getRepositoriesHomeDir().getAbsolutePath(), context.configuration().getWorkHomeDir().getAbsolutePath()); File workTree = new File(targetPath); workTree.mkdirs(); Repository workRepo = new RepositoryBuilder().setWorkTree(workTree).build(); if (!workRepo.getDirectory().exists()) { workRepo.create(false); } return workRepo; }
@Test public void test() throws Exception { // prepare a new folder File localPath = File.createTempFile("TestGitRepository", ""); localPath.delete(); // create the directory Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git")); repository.create(false); System.out.println("Having repository: " + repository.getDirectory()); repository.close(); }
private File cloneDatasourceViewsGit(String datasourceName) throws Exception { File targetDir = getDatasourceViewsGit(datasourceName); // Create datasource views bare git repo Repository newRepo = new FileRepository(targetDir); if (!targetDir.exists()) { newRepo.create(true); } String remoteUrl = "file://" + targetDir.getAbsolutePath(); File tmp = getTmpDirectory(); File localRepo = new File(tmp, "opal-" + Long.toString(System.nanoTime())); JGitUtils.cloneRepository( localRepo.getParentFile(), localRepo.getName(), remoteUrl, false, null); return localRepo; }
public void setup() { if (hasDotGit()) { LOGGER.info("Git is already configured"); return; } if (person == null) { person = new PersonIdent("Roo Git Add-On", "*****@*****.**"); } try { final String repositoryPath = pathResolver.getFocusedIdentifier(Path.ROOT, Constants.DOT_GIT); final Repository repository = new FileRepositoryBuilder().readEnvironment().setGitDir(new File(repositoryPath)).build(); repository.create(); } catch (final Exception e) { throw new IllegalStateException("Could not initialize Git repository", e); } setConfig("user", "name", person.getName()); setConfig("user", "email", person.getEmailAddress()); setConfig("remote \"origin\"", "fetch", "+refs/heads/*:refs/remotes/origin/*"); setConfig("branch \"master\"", "remote", "origin"); setConfig("branch \"master\"", "merge", "refs/heads/master"); final String gitIgnore = pathResolver.getFocusedIdentifier(Path.ROOT, Constants.GITIGNORE_FILENAME); if (!fileManager.exists(gitIgnore)) { InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = FileUtils.getInputStream(getClass(), "gitignore-template"); outputStream = fileManager.createFile(gitIgnore).getOutputStream(); IOUtils.copy(inputStream, outputStream); } catch (final IOException e) { throw new IllegalStateException( "Could not install " + Constants.GITIGNORE_FILENAME + " file in project", e); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } }
// import a git repo in jgit data structures or create a new one private Repository createRepo(String repoDir, String gitDir) throws IOException { File gd = new File(gitDir); File rd = new File(repoDir); if (GitWorks.anew) { if (rd.exists()) FileUtils.delete(rd, FileUtils.RECURSIVE); if (!GitWorks.bare) rd.mkdirs(); if (gd.exists()) FileUtils.delete(gd, FileUtils.RECURSIVE); gd.mkdirs(); } FileRepositoryBuilder frb = new FileRepositoryBuilder(); if (!GitWorks.bare) frb.setWorkTree(rd); Repository repository = frb.setGitDir(gd) .readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .setMustExist(!GitWorks.anew) .build(); if (GitWorks.anew) repository.create(GitWorks.bare); return repository; }
@Override protected void run() throws Exception { if (localName != null && gitdir != null) throw die(CLIText.get().conflictingUsageOf_git_dir_andArguments); final URIish uri = new URIish(sourceUri); if (localName == null) { try { localName = uri.getHumanishName(); } catch (IllegalArgumentException e) { throw die(MessageFormat.format(CLIText.get().cannotGuessLocalNameFrom, sourceUri)); } } if (gitdir == null) gitdir = new File(localName, Constants.DOT_GIT).getAbsolutePath(); dst = new FileRepositoryBuilder().setGitDir(new File(gitdir)).build(); dst.create(); final StoredConfig dstcfg = dst.getConfig(); dstcfg.setBoolean("core", null, "bare", false); // $NON-NLS-1$ //$NON-NLS-2$ dstcfg.save(); db = dst; outw.print(MessageFormat.format(CLIText.get().initializedEmptyGitRepositoryIn, gitdir)); outw.println(); outw.flush(); saveRemote(uri); final FetchResult r = runFetch(); final Ref checkoutRef; if (branch == null) checkoutRef = guessHEAD(r); else { checkoutRef = r.getAdvertisedRef(Constants.R_HEADS + branch); if (checkoutRef == null) throw die(MessageFormat.format(CLIText.get().noSuchRemoteRef, branch)); } doCheckout(checkoutRef); }
@Test public void shareProjectWithAlreadyCreatedRepos() throws IOException, InterruptedException, JGitInternalException, GitAPIException { Repository repo1 = FileRepositoryBuilder.create( new File(new File(createProject(projectName1)).getParent(), ".git")); repo1.create(); repo1.close(); Repository repo2 = FileRepositoryBuilder.create(new File(createProject(projectName2), ".git")); repo2.create(); repo2.close(); Repository repo3 = FileRepositoryBuilder.create(new File(createProject(projectName3), ".git")); repo3.create(); Git git = new Git(repo3); git.add().addFilepattern(".").call(); git.commit() .setAuthor("A U Thior", "*****@*****.**") .setMessage("Created Project 3") .call(); repo3.close(); ExistingOrNewPage existingOrNewPage = sharingWizard.openWizard(projectName1, projectName2, projectName3); existingOrNewPage.setInternalMode(true); // initial state IWorkspace workspace = ResourcesPlugin.getWorkspace(); String projectPath1 = workspace.getRoot().getProject(projectName1).getLocation().toOSString(); String projectPath2 = workspace.getRoot().getProject(projectName2).getLocation().toOSString(); String projectPath3 = workspace.getRoot().getProject(projectName3).getLocation().toOSString(); existingOrNewPage.assertContents( new Row[] { new Row(true, projectName1, projectPath1, ".." + File.separator + ".git"), new Row( false, projectName2, projectPath2, "", new Row[] { new Row(false, ".", "", ".git"), new Row(false, "..", "", ".." + File.separator + ".git") }), new Row( false, projectName3, projectPath3, "", new Row[] { new Row(true, ".", "", ".git"), new Row(false, "..", "", ".." + File.separator + ".git") }) }, ""); bot.tree().getAllItems()[1].getItems()[0].check(); existingOrNewPage.assertEnabling(false, false, true); bot.button("Finish").click(); Thread.sleep(1000); assertEquals( repo1.getDirectory().getAbsolutePath(), RepositoryMapping.getMapping(workspace.getRoot().getProject(projectName1)) .getRepository() .getDirectory() .toString()); assertEquals( repo2.getDirectory().getAbsolutePath(), RepositoryMapping.getMapping(workspace.getRoot().getProject(projectName2)) .getRepository() .getDirectory() .toString()); }
@Test public void testCheckoutBranchFromSecondaryRemote() throws Exception { // dummy commit to start off a new branch on origin createFile(testFile.toURI(), "origin-test"); Git git = new Git(db); git.add().addFilepattern(".").call(); git.commit().setMessage("test commit").call(); git.branchCreate().setName("test").setStartPoint(Constants.HEAD).call(); URI workspaceLocation = createWorkspace(getMethodName()); JSONObject projectTop = createProjectOrLink(workspaceLocation, getMethodName() + "-top", null); IPath clonePathTop = new Path("file").append(projectTop.getString(ProtocolConstants.KEY_ID)).makeAbsolute(); JSONObject projectFolder = createProjectOrLink(workspaceLocation, getMethodName() + "-folder", null); IPath clonePathFolder = new Path("file") .append(projectFolder.getString(ProtocolConstants.KEY_ID)) .append("folder") .makeAbsolute(); IPath[] clonePaths = new IPath[] {clonePathTop, clonePathFolder}; for (IPath clonePath : clonePaths) { // clone a repo JSONObject clone = clone(clonePath); String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION); String branchesLocation = clone.getString(GitConstants.KEY_BRANCH); String remotesLocation = clone.getString(GitConstants.KEY_REMOTE); // get project/folder metadata WebRequest request = getGetFilesRequest(cloneContentLocation); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // expect only origin getRemote(remotesLocation, 1, 0, Constants.DEFAULT_REMOTE_NAME); // create secondary repository IPath randomLocation = getRandomLocation(); randomLocation = randomLocation.addTrailingSeparator().append(Constants.DOT_GIT); File dotGitDir = randomLocation.toFile().getCanonicalFile(); Repository db2 = new FileRepository(dotGitDir); assertFalse(dotGitDir.exists()); db2.create(false /* non bare */); Git git2 = new Git(db2); // dummy commit to start off new branch File branchFile = new File(dotGitDir.getParentFile(), "branch.txt"); branchFile.createNewFile(); createFile(branchFile.toURI(), "secondary-branch"); git2.add().addFilepattern(".").call(); git2.commit().setMessage("branch commit").call(); git2.branchCreate().setName("branch").setStartPoint(Constants.HEAD).call(); // create remote response = addRemote(remotesLocation, "secondary", dotGitDir.getParentFile().toURL().toString()); String secondaryRemoteLocation = response.getHeaderField(ProtocolConstants.HEADER_LOCATION); assertNotNull(secondaryRemoteLocation); // list remotes request = getGetRequest(remotesLocation); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject remotes = new JSONObject(response.getText()); JSONArray remotesArray = remotes.getJSONArray(ProtocolConstants.KEY_CHILDREN); // expect origin and new remote assertEquals(2, remotesArray.length()); // fetch both remotes fetch(remotesArray.getJSONObject(0).getString(ProtocolConstants.KEY_LOCATION)); fetch(remotesArray.getJSONObject(1).getString(ProtocolConstants.KEY_LOCATION)); // secondary request = getGetRequest(remotesArray.getJSONObject(1).getString(ProtocolConstants.KEY_LOCATION)); response = webConversation.getResponse(request); JSONObject remote = waitForTaskCompletion(response); // checkout remote branch: secondary/branch String remoteBranchName = remote .getJSONArray(ProtocolConstants.KEY_CHILDREN) .getJSONObject(0) .getString(ProtocolConstants.KEY_NAME); if (!remoteBranchName.equals("secondary/branch")) remoteBranchName = remote .getJSONArray(ProtocolConstants.KEY_CHILDREN) .getJSONObject(1) .getString(ProtocolConstants.KEY_NAME); assertEquals("secondary/branch", remoteBranchName); response = branch(branchesLocation, "branch", remoteBranchName); JSONObject branch = new JSONObject(response.getText()); JSONArray remoteBranchLocations = branch.getJSONArray(GitConstants.KEY_REMOTE); assertEquals(1, remoteBranchLocations.length()); assertEquals( "secondary", remoteBranchLocations.getJSONObject(0).getString(ProtocolConstants.KEY_NAME)); assertEquals( "secondary/branch", remoteBranchLocations .getJSONObject(0) .getJSONArray(ProtocolConstants.KEY_CHILDREN) .getJSONObject(0) .getString(ProtocolConstants.KEY_NAME)); // origin request = getGetRequest(remotesArray.getJSONObject(0).getString(ProtocolConstants.KEY_LOCATION)); response = webConversation.getResponse(request); remote = waitForTaskCompletion(response); // checkout remote branch: origin/test JSONArray remoteChildren = remote.getJSONArray(ProtocolConstants.KEY_CHILDREN); assertEquals(2, remoteChildren.length()); remoteBranchName = remoteChildren.getJSONObject(0).getString(ProtocolConstants.KEY_NAME); if (!remoteBranchName.equals("origin/test")) remoteBranchName = remoteChildren.getJSONObject(1).getString(ProtocolConstants.KEY_NAME); assertEquals("origin/test", remoteBranchName); response = branch(branchesLocation, "test", remoteBranchName); branch = new JSONObject(response.getText()); remoteBranchLocations = branch.getJSONArray(GitConstants.KEY_REMOTE); assertEquals(1, remoteBranchLocations.length()); assertEquals( "origin", remoteBranchLocations.getJSONObject(0).getString(ProtocolConstants.KEY_NAME)); assertEquals( "origin/test", remoteBranchLocations .getJSONObject(0) .getJSONArray(ProtocolConstants.KEY_CHILDREN) .getJSONObject(0) .getString(ProtocolConstants.KEY_NAME)); } }