I need to print the status of committed files in JGit,whether it is added ,removed,changed etc.For that i have initially cloned the remote repository and I got the details of commit id,author name,author mail id,date and time.But when I try to print the status using IndexDiff/Status classes, I get null values.
I need to know is it possible to get status of committed files in a remote repository with or without cloning.
public static void main(String[] args)throws IOException, InvalidRemoteException, TransportException, GitAPIException {
String remote = "http://192.168.215.29:9090/technology-evaluation/patchgitpluginsample.git";
File localPath = File.createTempFile("TestGitRepository", "");
localPath.delete();
Git git = Git.cloneRepository().setURI(remote)
.setCredentialsProvider(new UsernamePasswordCredentialsProvider("sarathb", "findme"))
.setDirectory(localPath)
.call();
Repository repository = FileRepositoryBuilder.create(new File(localPath.getAbsolutePath(), ".git"));
System.out.println(repository);
List<Ref> branches = git.branchList().call();
for (Ref ref : branches)
{
System.out.println(ref.getName());
}
Iterable<RevCommit> commits = git.log().all().call();
for (RevCommit revCommit : commits) {
System.out.println("");
RevTree tree=revCommit.getTree();
/*System.out.println(revCommit.getName());*/
System.out.println("COMMIT : "+revCommit);
System.out.println("COMMIT MESSAGE : "+revCommit.getFullMessage());
System.out.println("AUTHOR NAME : "+revCommit.getAuthorIdent().getName());
System.out.println("AUTHOR E-MAIL ID : "+revCommit.getAuthorIdent().getEmailAddress());
System.out.println("DATE/TIME : "+revCommit.getAuthorIdent().getWhen());
Status status=git.status().call();
System.out.println("added:"+status.getAdded());
System.out.println("removed:"+status.getRemoved());
TreeWalk treewalk = new TreeWalk(repository);
treewalk.addTree(tree);
treewalk.setRecursive(true);
while (treewalk.next())
{
if(treewalk.getNameString().contains(".java"))
System.out.println("FILE COMMITTED : "+treewalk.getNameString());
}
}}}
Related
I would to use Apache SSHD to create an SFTP server and use SftpFileSystemProvider to mount a remote directory.
I successfully create the virtual file system with SftpFileSystemProvider following the documentation https://github.com/apache/mina-sshd/blob/master/docs/sftp.md#using-sftpfilesystemprovider-to-create-an-sftpfilesystem.
However I'm stuck when mouting remote directory even with the documentation https://github.com/apache/mina-sshd/blob/master/docs/sftp.md#configuring-the-sftpfilesystemprovider. It keeps mouting the root directory instead of the target one.
I tried:
adding the target directory into the sftp uri (not working)
getting new filesystem from path (not working)
Here is a quick example.
object Main:
class Events extends SftpEventListener
class Auth extends PasswordAuthenticator {
override def authenticate(username: String, password: String, session: ServerSession): Boolean = {
true
}
}
class FilesSystem extends VirtualFileSystemFactory {
override def createFileSystem(session: SessionContext): FileSystem = {
val uri = new URI("sftp://xxx:yyy#host/plop")
// val uri = SftpFileSystemProvider.createFileSystemURI("host", 22, "xxx", "yyy")
val fs = Try(FileSystems.newFileSystem(uri, Collections.emptyMap[String, Object](), new SftpFileSystemProvider().getClass().getClassLoader())) match {
case Failure(exception) =>
println("Failed to mount bucket")
println(exception.getMessage)
throw exception
case Success(filesSystem) =>
println("Bucket mounted")
filesSystem
}
//fs.getPath("plop").getFileSystem
fs
}
}
private val fs = new FilesSystem()
private val sftpSubSystem = new SftpSubsystemFactory.Builder().build()
sftpSubSystem.addSftpEventListener(new Events())
private val sshd: SshServer = SshServer.setUpDefaultServer()
sshd.setPort(22)
sshd.setHost("0.0.0.0")
sshd.setSubsystemFactories(Collections.singletonList(sftpSubSystem))
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get("hostkey.ser")))
sshd.setShellFactory(new InteractiveProcessShellFactory())
sshd.setCommandFactory(new ScpCommandFactory())
sshd.setFileSystemFactory(fs)
sshd.setPasswordAuthenticator(new Auth())
sshd.setSessionHeartbeat(HeartbeatType.IGNORE, Duration.ofSeconds(30L))
#main def m() = {
sshd.start()
while (sshd.isStarted) {
}
}
end Main
Am I missing something ?
SSHD version 2.8.0, SFTP protocol version 3, Scala3, Java11
I could be wrong, but, I think that these two ...
sshd.setShellFactory(new InteractiveProcessShellFactory())
sshd.setCommandFactory(new ScpCommandFactory())
sshd.setFileSystemFactory(fs)
... are redundant and this ...
private val sftpSubSystem = new SftpSubsystemFactory.Builder().build()
... needs to be made aware of the virtual file system.
i'm trying to use firebase storage to upload images.
and here is what I've tried.
public void firetalk(string path)
{
Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;
Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://<myurl>.appspot.com/");
Firebase.Storage.StorageReference art_image_ref = storage_ref.Child("images/innocence.jpg");
art_image_ref.PutFileAsync(path).ContinueWith((Task<StorageMetadata> task) =>
{
if (task.IsFaulted || task.IsCanceled)
{
Debug.Log(task.Exception.ToString());
// Uh-oh, an error occurred!
}
else
{
// Metadata contains file metadata such as size, content-type, and download URL.
Firebase.Storage.StorageMetadata metadata = task.Result;
string download_url = metadata.DownloadUrl.ToString();
Debug.Log("Finished uploading...");
Debug.Log("download url = " + download_url);
}
});
}
the firetalk funtion recieves a path and i use PutFileAsync for using the upload using path ,however i'm getting this error..
System.AggregateException: Exception of type 'System.AggregateException' was thrown.
-----------------
Firebase.Storage.StorageException: Permission denied. Could not perform this operation
UnityEngine.Debug:Log(Object)
GracesGames.SimpleFileBrowser.Scripts.explorer_script:m__0(Task`1) (at Assets/scripts/explorer_script.cs:85)
System.Threading.Tasks.TaskCompletionSource`1:SetException(Exception)
Firebase.Storage.StorageReference:CompleteTask(Task`1, TaskCompletionSource`1, Func`1, String, Boolean)
Firebase.Storage.c__AnonStorey6:<>m__0(Task`1)
System.Threading.Tasks.TaskCompletionSource`1:SetException(Exception)
Firebase.Storage.c__AnonStorey0:<>m__0()
Firebase.Storage.Future_StorageMetadata:SWIG_CompletionDispatcher(Int32)
Firebase.AppUtilPINVOKE:PollCallbacks()
Firebase.AppUtil:PollCallbacks()
Firebase.Platform.FirebaseAppUtils:PollCallbacks()
Firebase.Platform.FirebaseHandler:Update()
Firebase.Platform.FirebaseMonoBehaviour:Update()
any gueses?
I wrote a Spock test to learn how to use JGit. The general idea of the test follows these steps:
Create a "TestRepo" directory
Initialize a new Git repository there ("TestRepo/.git")
Create a new File in the parent directory (TestRepo) and set its text to something to take up space
Call "git status"
(debug) Groovy dump the returned Status object
Assert that the returned Status object has the file listed as untracked.
When I run the below test, it fails. Why?
state.dump() prints
Status#38989dff
diff=org.eclipse.jgit.lib.IndexDiff#72def3cd
clean=true
hasUncommittedChanges=false
Code below:
class GitActionsSpec extends Specification {
public static final ROOT_DIR_PATH = Paths.get(System.getProperty("user.home"), "TestRepo")
public static final ROOT_DIR_STRING = ROOT_DIR_PATH.toString()
public static final GIT_DIR_PATH = ROOT_DIR_PATH.resolve(".git")
#Shared
Git git
/**
* Creates a repository in rootDirPath
*/
def setupSpec() {
if (Files.exists(ROOT_DIR_PATH)) {
deleteDirectory(ROOT_DIR_PATH)
}
Files.createDirectory(ROOT_DIR_PATH)
/*
GitActions.createRepoIn(File parentDirectory) {
return Git.init().setDirectory(f).call()
}
*/
git = GitActions.createRepoIn(ROOT_DIR_PATH.toFile())
assert git.repository.getDirectory().exists()
}
// The actual test
def "A newly-created file should be listed as 'untracked'"() {
given: "A new file"
Path file = ROOT_DIR_PATH.relativize(ROOT_DIR_PATH.resolve("file.txt"))
file.text = "filler text"
assert Files.exists(file)
when: "user requests the status"
Status state = git.status().addPath(file.toString()).call()
then: "Git lists that file as untracked"
println state.dump()
!state.getUntracked().isEmpty()
}
def cleanupSpec() {
git.close()
deleteDirectory(ROOT_DIR_PATH)
}
def deleteDirectory(Path directory) {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
#Override
FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir)
return FileVisitResult.CONTINUE
}
#Override
FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file)
return FileVisitResult.CONTINUE
}
})
}
}
Turns out the issue lied in the code that sets up file.
File's toString() returns A, not B:
A: /home/user/Project/Module/file.txt
B: /home/user/TestRepo/file.txt
I want to know all the folders name under "Company Home" directory in Alfresco but getting error.
Code -
ItemIterable<QueryResult> results = session.query("SELECT * FROM cmis:folder where IN_TREE('/Company Home')", false);
try {
for (QueryResult result : results) {
folderId = result.getPropertyValueById(PropertyIds.OBJECT_ID);
Folder folder = (Folder) session.getObject(folderId);
System.out.println("Folder Name " + folder.getName());
}
} catch(Exception e) {
e.printStackTrace();
}
Error -
org.apache.chemistry.opencmis.commons.exceptions.CmisRuntimeException: 00270668 Request failed 500 /solr/alfresco/cmis?wt=json&fl=DBID%2Cscore&rows=100&df=TEXT&start=0&locale=en_US&fq=%7B%21afts%7DAUTHORITY_FILTER_FROM_JSON&fq=%7B%21afts%7DTENANT_FILTER_FROM_JSON
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.convertStatusCode(AbstractAtomPubService.java:452)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.post(AbstractAtomPubService.java:570)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.DiscoveryServiceImpl.query(DiscoveryServiceImpl.java:142)
at org.apache.chemistry.opencmis.client.runtime.SessionImpl$3.fetchPage(SessionImpl.java:567)
at org.apache.chemistry.opencmis.client.runtime.util.AbstractIterator.getCurrentPage(AbstractIterator.java:132)
at org.apache.chemistry.opencmis.client.runtime.util.CollectionIterator.hasNext(CollectionIterator.java:48)
at main.java.org.apache.chemistry.opencmis.doc.QueryTest.folderName(QueryTest.java:180)
IN_TREE takes the object id, not the the object path. If you provide the id of the "Company Home" folder, this query should work.
Company Home is the root folder, I suggest you use something like the following:
Session session = createSession();
Folder rootFolder = session.getRootFolder();
ItemIterable<CmisObject> children = rootFolder.getChildren();
for (CmisObject child : children) {
System.out.println(child.getName());
}
I clone a repository as bare on my local disk using JGit. Now, I need to read the contents of a file at any given commit id (SHA1). How do I do this ?
The comment of RĂ¼diger Herrmann in this answer contains the relevant hints; but to make it easier for the friends of copy & paste solutions here my complete self-contained example code of a junit test that creates a revision of a file and then retrieves the contents of this revision. Works with jGit 4.2.0.
#Test
public void test() throws IOException, GitAPIException
{
//
// init the git repository in a temporary directory
//
File repoDir = Files.createTempDirectory("jgit-test").toFile();
Git git = Git.init().setDirectory(repoDir).call();
//
// add file with simple text content
//
String testFileName = "testFile.txt";
File testFile = new File(repoDir, testFileName);
writeContent(testFile, "initial content");
git.add().addFilepattern(testFileName).call();
RevCommit firstCommit = git.commit().setMessage("initial commit").call();
//
// given the "firstCommit": use its "tree" and
// localize the test file by its name with the help of a tree parser
//
Repository repository = git.getRepository();
try (ObjectReader reader = repository.newObjectReader())
{
CanonicalTreeParser treeParser = new CanonicalTreeParser(null, reader, firstCommit.getTree());
boolean haveFile = treeParser.findFile(testFileName);
assertTrue("test file in commit", haveFile);
assertEquals(testFileName, treeParser.getEntryPathString());
ObjectId objectForInitialVersionOfFile = treeParser.getEntryObjectId();
// now we have the object id of the file in the commit:
// open and read it from the reader
ObjectLoader oLoader = reader.open(objectForInitialVersionOfFile);
ByteArrayOutputStream contentToBytes = new ByteArrayOutputStream();
oLoader.copyTo(contentToBytes);
assertEquals("initial content", new String(contentToBytes.toByteArray(), "utf-8"));
}
git.close();
}
// simple helper to keep the main code shorter
private void writeContent(File testFile, String content) throws IOException
{
try (OutputStreamWriter wr = new OutputStreamWriter(new FileOutputStream(testFile), Charset.forName("utf-8")))
{
wr.append(content);
}
}
Edit to add: another, probably better example is at https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/ReadFileFromCommit.java
By using this. Iterable<RevCommit> gitLog = gitRepo.log().call(); you can get all the commit hash from that object.