/** * Checks if given folder is a git repository * * @param folder * to check * * @return true if it is a git repository, false otherwise. */ public boolean isValidGitRepository(Path folder) { if (Files.exists(folder) && Files.isDirectory(folder)) { // If it has been at least initialized if (RepositoryCache.FileKey.isGitRepository(folder.toFile(), FS.DETECTED)) { // we are assuming that the clone worked at that time, caller should call hasAtLeastOneReference return true; } else { return false; } } else { return false; } }
public static List<File> reposInDefaultRepoDir() { File reposDir = new File(getExternalStorageDirectory(), "git-repos"); List<File> repos = newArrayList(); if (!reposDir.exists() && !reposDir.mkdirs()) { Log.d(TAG, "Could not create default repos dir " + reposDir); return repos; } for (File repoDir : reposDir.listFiles()) { File gitdir = RepositoryCache.FileKey.resolve(repoDir, FS.detect()); if (gitdir != null) { repos.add(gitdir); } } Log.d(TAG, "Found " + repos.size() + " repos in " + reposDir); return repos; }
/** * Returns the JGit repository for the specified name. * * @param repositoryName * @param logError * @return repository or null */ public Repository getRepository(String repositoryName, boolean logError) { if (isCollectingGarbage(repositoryName)) { logger.warn(MessageFormat.format("Rejecting request for {0}, busy collecting garbage!", repositoryName)); return null; } File dir = FileKey.resolve(new File(repositoriesFolder, repositoryName), FS.DETECTED); if (dir == null) return null; Repository r = null; try { FileKey key = FileKey.exact(dir, FS.DETECTED); r = RepositoryCache.open(key, true); } catch (IOException e) { if (logError) { logger.error("GitBlit.getRepository(String) failed to find " + new File(repositoriesFolder, repositoryName).getAbsolutePath()); } } return r; }
public static void close(Repository r) { RepositoryCache.close(r); // assume 2 uses in case reflection fails int uses = 2; try { Field useCnt = Repository.class.getDeclaredField("useCnt"); useCnt.setAccessible(true); uses = ((AtomicInteger) useCnt.get(r)).get(); } catch (Exception e) { e.printStackTrace(); } for (int i = 0; i < uses; i++) { r.close(); } }
@Test public void testCreateRepository() throws Exception { String[] repositories = { "NewTestRepository.git", "NewTestRepository" }; for (String repositoryName : repositories) { Repository repository = JGitUtils.createRepository(GitBlitSuite.REPOSITORIES, repositoryName); File folder = FileKey.resolve(new File(GitBlitSuite.REPOSITORIES, repositoryName), FS.DETECTED); assertNotNull(repository); assertFalse(JGitUtils.hasCommits(repository)); assertNull(JGitUtils.getFirstCommit(repository, null)); assertEquals(folder.lastModified(), JGitUtils.getFirstChange(repository, null) .getTime()); assertEquals(folder.lastModified(), JGitUtils.getLastChange(repository).getTime()); assertNull(JGitUtils.getCommit(repository, null)); repository.close(); RepositoryCache.close(repository); FileUtils.delete(repository.getDirectory(), FileUtils.RECURSIVE); } }
public GitVersionControl(Path path) throws IOException { try { // Cribbed from Git.open, but with findGitDir rather than setGitDir // and extracting the location. FS fs = FS.DETECTED; RepositoryCache.FileKey key = RepositoryCache.FileKey.lenient(path.toFile(), fs); RepositoryBuilder builder = new RepositoryBuilder() .setFS(fs) .findGitDir(key.getFile()) .setMustExist(true); repositoryRoot = Paths.get(builder.getGitDir().getAbsolutePath()).getParent(); repo = new Git(builder.build()); checkMergeDriver(repositoryRoot); } catch (RuntimeException ex) { throw new IOException(ex); } }
/** 초기화 메서드 * @param creatorName * @param repositoryName */ public void Init(String creatorName, String repositoryName) { try { this.path = gitPath + creatorName + "/" + repositoryName + ".git"; this.localRepo = RepositoryCache.open(RepositoryCache.FileKey .lenient(new File(this.path), FS.DETECTED), true); this.git = new Git(localRepo); } catch (Exception e) { System.err.println(e.getMessage()); } }
/** 초기화 메서드 * @param creatorName * @param repositoryName */ public void Init(String path) { try { this.path = path+ "/.git"; this.localRepo = RepositoryCache.open(RepositoryCache.FileKey .lenient(new File(this.path), FS.DETECTED), true); this.git = new Git(localRepo); } catch (Exception e) { System.err.println(e.getMessage()); } }
@Override protected void save(PersonIdent ident, String msg) throws IOException, ConfigInvalidException { super.save(ident, msg); // we need to invalidate the JGit cache if the group list is invalidated in // an unattended init step RepositoryCache.clear(); }
@Override public void close() throws Exception { try { checkNoteDbState(); } finally { daemon.getLifecycleManager().stop(); if (daemonService != null) { System.out.println("Gerrit Server Shutdown"); daemonService.shutdownNow(); daemonService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); } RepositoryCache.clear(); } }
private void createRepository(Path directory, Project.NameKey projectName) throws IOException { String n = projectName.get() + Constants.DOT_GIT_EXT; FileKey loc = FileKey.exact(directory.resolve(n).toFile(), FS.DETECTED); try (Repository db = RepositoryCache.open(loc, false)) { db.create(true /* bare */); } }
private void createRepository(Path directory, String projectName) throws IOException { String n = projectName + Constants.DOT_GIT_EXT; FileKey loc = FileKey.exact(directory.resolve(n).toFile(), FS.DETECTED); try (Repository db = RepositoryCache.open(loc, false)) { db.create(true /* bare */); } }
public GithubRepository(String remoteUrl, String localDir, boolean needsPassword) { this.remoteUrl = remoteUrl; this.needsPassword = needsPassword; File f = new File(remoteUrl); String localPath = localDir + File.separator + f.getName().replace(".git", ""); rootDirectory = new File(localPath); gitDirectory = new File(localPath + File.separator + ".git"); cloned = false; if (RepositoryCache.FileKey.isGitRepository(this.getGitDirectory(), FS.DETECTED)) { cloned = true; } }
/** * Davide you might notice that I have made functions smaller. * It makes code immensely more readable and you quickly are able * to resume the code from where you left. * Understanding takes lesser time, as number of lines are lesser. * @return */ private boolean init_CheckDir_gitClone(){ //Check if the given directory exists boolean gitUpdated = true; if (RepositoryCache.FileKey.isGitRepository(new File(gitDirectory.getAbsolutePath(), ".git"), FS.DETECTED)) { // Already cloned. Just need to pull a repository here. System.out.println("git pull"); gitUpdated = gitPull(gitDirectory); } else { // Not present or not a Git repository. System.out.println("git clone"); gitClone(gitDirectory); }return gitUpdated; }
public static Repository openRepoFor(File gitdir) { try { Repository repo = RepositoryCache.open(FileKey.lenient(gitdir, FS.DETECTED), false); Log.d("REPO", "Opened " + describe(repo)); return repo; } catch (Exception e) { throw new RuntimeException(e); } }
public List<RepoRecord> getAllRepos() { registerReposInStandardDir(); List<RepoRecord> allRepos = newArrayList(); Set<Long> missingReposIds = newHashSet(); Cursor cursor = database.query(DatabaseHelper.TABLE_REPOS, new String[] { DatabaseHelper.COLUMN_ID, DatabaseHelper.COLUMN_GITDIR }, null, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { RepoRecord repoRecord = cursorToRepo(cursor); Log.d(TAG, "Found " + repoRecord); File currentGitDir = RepositoryCache.FileKey.resolve(repoRecord.gitdir, FILESYSTEM); if (currentGitDir == null) { missingReposIds.add(repoRecord.id); } else { allRepos.add(repoRecord); } cursor.moveToNext(); } cursor.close(); Log.d(TAG, "Found " + allRepos.size() + " repos, " + missingReposIds.size() + " missing repos"); for (Long repoId : missingReposIds) { Log.d(TAG, "Deleting missing repo..."); database.delete(DatabaseHelper.TABLE_REPOS, DatabaseHelper.COLUMN_ID + " = " + repoId, null); } return allRepos; }
@Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { MatrixCursor matrixCursor = new MatrixCursor(new String[] { "_id", "gitdir" }); for (File repoDir : reposDir.listFiles()) { File gitdir = RepositoryCache.FileKey.resolve(repoDir, FS.detect()); if (gitdir != null) { matrixCursor.newRow().add(gitdir.hashCode()).add(gitdir); } } return matrixCursor; }
@BeforeClass public void setup() throws Exception { cleanUpDir(TEST_DIR); // Create a bare repository RepositoryCache.FileKey fileKey = RepositoryCache.FileKey.exact(remoteDir, FS.DETECTED); this.remoteRepo = fileKey.open(false); this.remoteRepo.create(true); this.gitForPush = Git.cloneRepository().setURI(this.remoteRepo.getDirectory().getAbsolutePath()).setDirectory(cloneDir).call(); // push an empty commit as a base for detecting changes this.gitForPush.commit().setMessage("First commit").call(); this.gitForPush.push().setRemote("origin").setRefSpecs(this.masterRefSpec).call(); this.config = ConfigBuilder.create() .addPrimitive(ConfigurationKeys.GIT_CONFIG_MONITOR_REPO_URI, this.remoteRepo.getDirectory().getAbsolutePath()) .addPrimitive(ConfigurationKeys.GIT_CONFIG_MONITOR_REPO_DIR, TEST_DIR + "/jobConfig") .addPrimitive(ConfigurationKeys.FLOWSPEC_STORE_DIR_KEY, TEST_DIR + "flowCatalog") .addPrimitive(ConfigurationKeys.GIT_CONFIG_MONITOR_POLLING_INTERVAL, 5) .build(); this.flowCatalog = new FlowCatalog(config); this.flowCatalog.startAsync().awaitRunning(); this.gitConfigMonitor = new GitConfigMonitor(this.config, this.flowCatalog); this.gitConfigMonitor.setActive(true); }
/** * Ensure that a cached repository is completely closed and its resources * are properly released. * * @param repositoryName */ private void closeRepository(String repositoryName) { Repository repository = getRepository(repositoryName); if (repository == null) { return; } RepositoryCache.close(repository); // assume 2 uses in case reflection fails int uses = 2; try { // The FileResolver caches repositories which is very useful // for performance until you want to delete a repository. // I have to use reflection to call close() the correct // number of times to ensure that the object and ref databases // are properly closed before I can delete the repository from // the filesystem. Field useCnt = Repository.class.getDeclaredField("useCnt"); useCnt.setAccessible(true); uses = ((AtomicInteger) useCnt.get(repository)).get(); } catch (Exception e) { logger.warn(MessageFormat .format("Failed to reflectively determine use count for repository {0}", repositoryName), e); } if (uses > 0) { logger.info(MessageFormat .format("{0}.useCnt={1}, calling close() {2} time(s) to close object and ref databases", repositoryName, uses, uses)); for (int i = 0; i < uses; i++) { repository.close(); } } // close any open index writer/searcher in the Lucene executor luceneExecutor.close(repositoryName); }
public static void close(File repository) { try { File gitDir = FileKey.resolve(repository, FS.detect()); if (gitDir != null && gitDir.exists()) { close(RepositoryCache.open(FileKey.exact(gitDir, FS.detect()))); } } catch (Exception e) { e.printStackTrace(); } }
@Override public Repository openRepository(GitUser user, GitRepository repo, boolean mustExist) throws IOException { if (user == null) { if (!repo.isPublicRead()) { return null; } } else { if (!user.canAccess(repo)) { return null; } } final CloudKey loc = new CloudKey(repo, this); return RepositoryCache.open(loc, mustExist); }
@Override public boolean isInsideWorkTree() throws GitException { return RepositoryCache.FileKey.isGitRepository(getRepository().getDirectory(), FS.DETECTED); }
@Nullable private File getPathToAllUsersRepository() { Path basePath = site.resolve(flags.cfg.getString("gerrit", null, "basePath")); checkArgument(basePath != null, "gerrit.basePath must be configured"); return RepositoryCache.FileKey.resolve(basePath.resolve(allUsers).toFile(), FS.DETECTED); }
@Override public void run() { /* File tmpDir = new File(System.getProperty("java.io.tmpdir"), "tmp" + System.currentTimeMillis()); */ gitDirectory = new File("C:\\xampp\\htdocs\\nutest"); outputDirectory = new File("C:\\xampp\\htdocs\\nutestoutput"); boolean shouldUpdate = true; gitDirectory.mkdirs(); outputDirectory.mkdirs(); //Check if the given directory exists if (RepositoryCache.FileKey.isGitRepository(new File(gitDirectory.getAbsolutePath(), ".git"), FS.DETECTED)) { // Already cloned. Just need to pull a repository here. System.out.println("git pull"); shouldUpdate = gitPull(gitDirectory); } else { // Not present or not a Git repository. System.out.println("git clone"); gitClone(gitDirectory); } if (shouldUpdate) { System.out.println("Updating plugins zip"); try { NUCompiler compiler = new NUCompiler(gitDirectory); NUZipFileGenerator zipFileGenerator = new NUZipFileGenerator(gitDirectory, outputDirectory); //Compile components in order of dependency compiler.compileApi(); compiler.compileUtils(); compiler.compileIntAbsImpl(); compiler.compileUploaders(); //Create the zip files zipFileGenerator.createZipFiles(pluginsToUpdate); } catch (Exception ex) { Logger.getLogger(UpdaterGenerator.class.getName()).log(Level.SEVERE, null, ex); } finally { //removeDirectory(tmpDir); } } else { System.out.println("No need to update"); } }
private static File resolveGitDirFor(File folder) { return RepositoryCache.FileKey.resolve(folder, FS.detect()); }
private File existingRepoGitDir() { return RepositoryCache.FileKey.resolve(getTargetFolder(), FS.detect()); }
@BeforeClass public void setup() throws Exception { cleanUpDir(SERVICE_WORK_DIR); cleanUpDir(SPEC_STORE_PARENT_DIR); Properties serviceCoreProperties = new Properties(); serviceCoreProperties.put(ConfigurationKeys.TOPOLOGYSPEC_STORE_DIR_KEY, TOPOLOGY_SPEC_STORE_DIR); serviceCoreProperties.put(ConfigurationKeys.FLOWSPEC_STORE_DIR_KEY, FLOW_SPEC_STORE_DIR); serviceCoreProperties.put(ServiceConfigKeys.TOPOLOGY_FACTORY_TOPOLOGY_NAMES_KEY , TEST_GOBBLIN_EXECUTOR_NAME); serviceCoreProperties.put(ServiceConfigKeys.TOPOLOGY_FACTORY_PREFIX + TEST_GOBBLIN_EXECUTOR_NAME + ".description", "StandaloneTestExecutor"); serviceCoreProperties.put(ServiceConfigKeys.TOPOLOGY_FACTORY_PREFIX + TEST_GOBBLIN_EXECUTOR_NAME + ".version", FlowSpec.Builder.DEFAULT_VERSION); serviceCoreProperties.put(ServiceConfigKeys.TOPOLOGY_FACTORY_PREFIX + TEST_GOBBLIN_EXECUTOR_NAME + ".uri", "gobblinExecutor"); serviceCoreProperties.put(ServiceConfigKeys.TOPOLOGY_FACTORY_PREFIX + TEST_GOBBLIN_EXECUTOR_NAME + ".specExecutorInstance", "org.apache.gobblin.service.InMemorySpecExecutor"); serviceCoreProperties.put(ServiceConfigKeys.TOPOLOGY_FACTORY_PREFIX + TEST_GOBBLIN_EXECUTOR_NAME + ".specExecInstance.capabilities", TEST_SOURCE_NAME + ":" + TEST_SINK_NAME); serviceCoreProperties.put(ServiceConfigKeys.GOBBLIN_SERVICE_GIT_CONFIG_MONITOR_ENABLED_KEY, true); serviceCoreProperties.put(ConfigurationKeys.GIT_CONFIG_MONITOR_REPO_URI, GIT_REMOTE_REPO_DIR); serviceCoreProperties.put(ConfigurationKeys.GIT_CONFIG_MONITOR_REPO_DIR, GIT_LOCAL_REPO_DIR); serviceCoreProperties.put(ConfigurationKeys.GIT_CONFIG_MONITOR_POLLING_INTERVAL, 5); // Create a bare repository RepositoryCache.FileKey fileKey = RepositoryCache.FileKey.exact(new File(GIT_REMOTE_REPO_DIR), FS.DETECTED); fileKey.open(false).create(true); this.gitForPush = Git.cloneRepository().setURI(GIT_REMOTE_REPO_DIR).setDirectory(new File(GIT_CLONE_DIR)).call(); // push an empty commit as a base for detecting changes this.gitForPush.commit().setMessage("First commit").call(); this.gitForPush.push().setRemote("origin").setRefSpecs(new RefSpec("master")).call(); this.gobblinServiceManager = new GobblinServiceManager("CoreService", "1", ConfigUtils.propertiesToConfig(serviceCoreProperties), Optional.of(new Path(SERVICE_WORK_DIR))); this.gobblinServiceManager.start(); this.flowConfigClient = new FlowConfigClient(String.format("http://localhost:%s/", this.gobblinServiceManager.restliServer.getPort())); }