Browse Source

Closes #52 Moved to Log Activity, display result

isundil 7 years ago
parent
commit
e35fd36e16

+ 2 - 2
app/src/main/java/info/knacki/pass/git/BaseGitProtocol.java

@@ -89,12 +89,12 @@ public abstract class BaseGitProtocol implements GitInterface {
     protected abstract void OnBranchCreated();
 
     @Override
-    public void CreateBranch(String branchName, OnResponseListener<GitRef[]> callback) {
+    public void CreateBranch(String branchName, OnStreamResponseListener<GitRef[]> callback) {
         final GitCommit.Builder commit = new GitCommit.Builder(fConfig.GetUsername(), fConfig.GetUserEmail(), "init");
         PushPack(commit.Build(), new Pacman(commit.PreparePack()), "refs/heads/" +branchName, new OnStreamResponseListener<Void>() {
             @Override
             public void OnMsg(String message) {
-                log.info(message);
+                callback.OnMsg(message);
             }
 
             @Override

+ 1 - 1
app/src/main/java/info/knacki/pass/git/GitInterface.java

@@ -11,5 +11,5 @@ public interface GitInterface {
     void FetchHead(final OnStreamResponseListener<GitCommit> response);
     void FetchBlob(GitObject.GitBlob blob, OnStreamResponseListener<byte[]> response);
     void PushCommitBuilder(GitCommit.Builder commit, OnStreamResponseListener<Void> resp);
-    void CreateBranch(String branchName, OnResponseListener<GitRef[]> callback);
+    void CreateBranch(String branchName, OnStreamResponseListener<GitRef[]> callback);
 }

+ 9 - 27
app/src/main/java/info/knacki/pass/settings/ui/SettingsActivity.java

@@ -336,9 +336,9 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
                     if (branch.equals("0000")) {
                         AlertPromptGenerator.StaticMake(getActivity())
                                 .setView(new SimpleTextEdit(getActivity())
-                                    .setText("master"))
+                                        .setText("master"))
                                 .setTitle(R.string.new_branch)
-                                .setPositiveButton(R.string.ok, (d, v) -> CreateBranch(((SimpleTextEdit)v).getStr().trim()))
+                                .setPositiveButton(R.string.ok, (d, v) -> CreateBranch(((SimpleTextEdit) v).getStr().trim()))
                                 .setNegativeButton(R.string.cancel, null)
                                 .show();
                     } else {
@@ -350,39 +350,21 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
             });
 
             findPreference(getResources().getString(R.string.id_vcs_git_pull)).setOnPreferenceClickListener(preference -> {
-                startActivity(new Intent(getActivity(), GitPullActivity.class));
+                GitPullActivity.StartSyncActivity(getActivity());
                 return true;
             });
+        }
+
+        @Override
+        public void onResume() {
+            super.onResume();
             reload();
         }
 
         private final void CreateBranch(String branchName) {
             if (branchName.equals(""))
                 return;
-            final SettingsManager.VCS versioning = SettingsManager.GetVCS(getActivity());
-            if (versioning instanceof SettingsManager.Git) {
-                GitInterface gitInterface;
-                try {
-                    gitInterface = GitInterfaceFactory.factory((SettingsManager.Git) versioning);
-                }
-                catch (GitInterfaceFactory.GitInterfaceException e) {
-                    Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
-                    return;
-                }
-
-                gitInterface.CreateBranch(branchName, new OnResponseListener<GitRef[]>() {
-                    @Override
-                    public void OnResponse(GitRef[] result) {
-                        // TODO select new branch by default
-                        getActivity().runOnUiThread(() -> PopulateBranches((ListPreference) FindPreference(R.string.id_vcs_git_branches), (SettingsManager.Git) versioning, result));
-                    }
-
-                    @Override
-                    public void OnError(String msg, Throwable e) {
-                        getActivity().runOnUiThread(() -> Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show());
-                    }
-                });
-            }
+            GitPullActivity.StartCreateBranchActivity(getActivity(), branchName);
         }
 
         final SparseArray<Preference> hiddenPreferences = new SparseArray<>();

+ 148 - 70
app/src/main/java/info/knacki/pass/ui/GitPullActivity.java

@@ -1,5 +1,7 @@
 package info.knacki.pass.ui;
 
+import android.content.Context;
+import android.content.Intent;
 import android.os.Bundle;
 import android.support.v7.app.AppCompatActivity;
 import android.widget.ProgressBar;
@@ -24,6 +26,7 @@ import info.knacki.pass.git.GitLocal;
 import info.knacki.pass.git.GitSha1;
 import info.knacki.pass.git.entities.GitCommit;
 import info.knacki.pass.git.entities.GitObject;
+import info.knacki.pass.git.entities.GitRef;
 import info.knacki.pass.io.FileUtils;
 import info.knacki.pass.io.OnResponseListener;
 import info.knacki.pass.io.OnStreamResponseListener;
@@ -33,13 +36,23 @@ import info.knacki.pass.ui.alertPrompt.AlertPrompt;
 import info.knacki.pass.ui.alertPrompt.AlertPromptGenerator;
 import info.knacki.pass.ui.alertPrompt.views.ConflictView;
 
+import static info.knacki.pass.settings.SettingsManager.GetVCS;
+
 public class GitPullActivity extends AppCompatActivity {
     private final static Logger log = Logger.getLogger(GitPullActivity.class.getName());
     public final static String COMMIT_MSG = "Android pass sync";
     public static String LOCAL_GIT_HASH_VERSION_FILE;
 
-    private GitInterface fGitInterface;
-    private GitCommit fHeadCommit;
+    public final static String GIT_COMMAND = GitPullActivity.class.getName() +"_GIT_COMMAND";
+    public final static String BRANCH_NAME = GitPullActivity.class.getName() +"_BRANCH_NAME";
+    public final static char COMMAND_SYNC = 1;
+    public final static char COMMAND_CREATE_BRANCH = 2;
+
+    private class Status {
+        HashSet<String> filesToPush = new HashSet<>();
+        HashMap<String, GitObject.GitBlob> filesToPull = new HashMap<>();
+        HashMap<String, GitObject.GitBlob> conflictingFiles = new HashMap<>();
+    }
 
     private void OnMsg(final String msg) {
         log.info(msg);
@@ -49,59 +62,124 @@ public class GitPullActivity extends AppCompatActivity {
         });
     }
 
+    public static void StartSyncActivity(Context ctx) {
+        Intent i = new Intent(ctx, GitPullActivity.class);
+        i.putExtra(GIT_COMMAND, COMMAND_SYNC);
+        ctx.startActivity(i);
+    }
+
+    public static void StartCreateBranchActivity(Context ctx, String branchName) {
+        Intent i = new Intent(ctx, GitPullActivity.class);
+        i.putExtra(GIT_COMMAND, COMMAND_CREATE_BRANCH);
+        i.putExtra(BRANCH_NAME, branchName);
+        ctx.startActivity(i);
+    }
+
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        final SettingsManager.VCS versioning = SettingsManager.GetVCS(this);
+        final SettingsManager.VCS versioning = GetVCS(this);
 
         setContentView(R.layout.activity_git_pull);
         setTitle(R.string.pref_vcs_git_pull);
+        findViewById(R.id.close_bt).setOnClickListener(v -> GitPullActivity.this.finish());
+
+        LOCAL_GIT_HASH_VERSION_FILE = PathUtils.GetGitFile(this);
 
         if (!(versioning instanceof SettingsManager.Git)) {
             finish();
             return;
         }
-        LOCAL_GIT_HASH_VERSION_FILE = PathUtils.GetGitFile(this);
+        final GitInterface gitInterface;
         try {
-            fGitInterface = GitInterfaceFactory.factory((SettingsManager.Git) versioning);
-            fGitInterface.FetchHead(new OnStreamResponseListener<GitCommit>() {
-                @Override
-                public void OnMsg(final String msg) {
-                    GitPullActivity.this.OnMsg(msg);
-                }
-
-                @Override
-                public void OnResponse(GitCommit result) {
-                    fHeadCommit = result;
-                    GitPullActivity.this.runOnUiThread(GitPullActivity.this::OnTreeStructureFetched);
-                }
-
-                @Override
-                public void OnError(final String msg, Throwable e) {
-                    GitPullActivity.this.runOnUiThread(() -> {
-                        OnMsg(msg);
-                        FinishLoading();
-                    });
-                }
-            });
+            gitInterface = GitInterfaceFactory.factory((SettingsManager.Git) versioning);
         } catch (GitInterfaceFactory.GitInterfaceException e) {
             GitPullActivity.this.runOnUiThread(() -> {
                 OnMsg(e.getMessage());
                 FinishLoading();
             });
+            return;
         }
-        findViewById(R.id.close_bt).setOnClickListener(v -> GitPullActivity.this.finish());
+
+        final char command = getIntent().getCharExtra(GIT_COMMAND, (char) 0);
+        if (COMMAND_SYNC == command)
+            FetchHead(gitInterface);
+        else if (COMMAND_CREATE_BRANCH == command)
+            CreateBranch(gitInterface, getIntent().getStringExtra(BRANCH_NAME));
+        else
+            finish();
+    }
+
+    private void CreateBranch(GitInterface gitInterface, String branchName) {
+        if (branchName == null)
+            finish();
+        OnMsg("Creating branch " +branchName);
+        final String trimmedBranchName = branchName.trim();
+        if ("".equals(trimmedBranchName)) {
+            OnMsg("Invalid branch name");
+            finish();
+        }
+
+        OnMsg("Pushing to origin");
+        gitInterface.CreateBranch(trimmedBranchName, new OnStreamResponseListener<GitRef[]>() {
+            @Override
+            public void OnResponse(GitRef[] result) {
+                runOnUiThread(GitPullActivity.this::FinishLoading);
+                for (GitRef i: result)
+                    if (i.GetBranchName().equals(trimmedBranchName)) {
+                        SettingsManager.VCS git = SettingsManager.GetVCS(GitPullActivity.this);
+                        if (git instanceof SettingsManager.Git) {
+                            ((SettingsManager.Git) git).SetBranch(i.GetBranch());
+                            SettingsManager.SetVCS(GitPullActivity.this, git);
+                            OnMsg("Branch set up to track " +i.GetBranch());
+                        }
+                    }
+            }
+
+            @Override
+            public void OnError(String msg, Throwable e) {
+                runOnUiThread(() -> {
+                    GitPullActivity.this.OnMsg(msg);
+                    FinishLoading();
+                });
+            }
+
+            @Override
+            public void OnMsg(String msg) {
+                runOnUiThread(() -> GitPullActivity.this.OnMsg(msg));
+            }
+        });
     }
 
-    protected void OnTreeStructureFetched() {
+    private void FetchHead(GitInterface gitInterface) {
+        gitInterface.FetchHead(new OnStreamResponseListener<GitCommit>() {
+            @Override
+            public void OnMsg(final String msg) {
+                GitPullActivity.this.OnMsg(msg);
+            }
+
+            @Override
+            public void OnResponse(GitCommit result) {
+                GitPullActivity.this.runOnUiThread(() -> GitPullActivity.this.OnTreeStructureFetched(gitInterface, result));
+            }
+
+            @Override
+            public void OnError(final String msg, Throwable e) {
+                GitPullActivity.this.runOnUiThread(() -> {
+                    OnMsg(msg);
+                    FinishLoading();
+                });
+            }
+        });
+    }
+
+    private void OnTreeStructureFetched(GitInterface gitInterface, GitCommit headCommit) {
         final GitLocal localVersion = new GitLocal(new File(LOCAL_GIT_HASH_VERSION_FILE));
-        HashMap<String, GitObject.GitBlob> filesToPull = new HashMap<>();
-        Set<String> filesToPush = new HashSet<>();
-        HashMap<String, GitObject.GitBlob> conflictingFiles = new HashMap<>();
+        Status status = new Status();
 
         OnMsg("Done reading remote tree");
         OnMsg("Building change list");
-        for (Map.Entry<String, GitObject.GitBlob>i: fHeadCommit.GetTree().FindAllBlobs().entrySet()) {
+        for (Map.Entry<String, GitObject.GitBlob>i: headCommit.GetTree().FindAllBlobs().entrySet()) {
             final String remoteKnownHash = localVersion.GetHash(i.getKey(), "");
             final String remoteHash = GitSha1.BytesToString(i.getValue().GetHash());
             final String currentHash = GitSha1.BytesToString(GitSha1.getRawSha1OfFile(new File(PathUtils.GetPassDir(this) +i.getKey())));
@@ -112,47 +190,47 @@ public class GitPullActivity extends AppCompatActivity {
             if (remoteChanged && localChanged) {
                 // Conflict (but file can still has the same content)
                 if (currentHash.equals(remoteHash))
-                    filesToPull.put(i.getKey(), i.getValue());
+                    status.filesToPull.put(i.getKey(), i.getValue());
                 else
-                    conflictingFiles.put(i.getKey(), i.getValue());
+                    status.conflictingFiles.put(i.getKey(), i.getValue());
             } else if (remoteChanged) {
                 // remote changed
-                filesToPull.put(i.getKey(), i.getValue());
+                status.filesToPull.put(i.getKey(), i.getValue());
             } else if (localChanged) {
                 // local changed
-                filesToPush.add(i.getKey());
+                status.filesToPush.add(i.getKey());
             }
         }
         for (String i: localVersion.FileNames()) {
-            if (fHeadCommit.GetTree().GetObjectFullPath(i) == null) {
+            if (headCommit.GetTree().GetObjectFullPath(i) == null) {
                 log.finer("removed from remote " +i);
                 final String currentHash = GitSha1.BytesToString(GitSha1.getRawSha1OfFile(new File(PathUtils.GetPassDir(this) +i)));
                 final boolean localChanged = !currentHash.equals(localVersion.GetHash(i, ""));
 
                 if (!localChanged || "".equals(currentHash))
-                    filesToPull.put(i, null);
+                    status.filesToPull.put(i, null);
                 else
-                    conflictingFiles.put(i, null);
+                    status.conflictingFiles.put(i, null);
             }
         }
-        CheckNewFiles(localVersion, new File(PathUtils.GetPassDir(this)), "", filesToPull.keySet(), filesToPush, conflictingFiles.keySet());
-        if (conflictingFiles.isEmpty())
-            SyncFiles(localVersion, filesToPull, filesToPush);
+        CheckNewFiles(localVersion, new File(PathUtils.GetPassDir(this)), "", status);
+        if (status.conflictingFiles.isEmpty())
+            SyncFiles(localVersion, gitInterface, headCommit, status);
         else
-            AskForConflicts(localVersion, conflictingFiles, filesToPull, filesToPush);
+            AskForConflicts(localVersion, gitInterface, headCommit, status);
     }
 
-    int CheckNewFiles(GitLocal localVersion, File root, String rootPath, Set<String> filesToPull, Set<String> filesToPush, Set<String> conflicts) {
+    private int CheckNewFiles(GitLocal localVersion, File root, String rootPath, Status status) {
         int newFiles = 0;
         for (final File i: root.listFiles()) {
             if (!PathUtils.IsHidden(i.getAbsolutePath())) {
                 if (i.isDirectory()) {
-                    newFiles += CheckNewFiles(localVersion, i, rootPath + "/" + i.getName(), filesToPull, filesToPush, conflicts);
+                    newFiles += CheckNewFiles(localVersion, i, rootPath + "/" + i.getName(), status);
                 } else if (i.isFile()) {
                     String path = rootPath + "/" + i.getName();
-                    if (!localVersion.HasHash(path) && !filesToPull.contains(path) && !conflicts.contains(path)) {
+                    if (!localVersion.HasHash(path) && !status.filesToPull.containsKey(path) && !status.conflictingFiles.containsKey(path)) {
                         // New file
-                        filesToPush.add(path);
+                        status.filesToPush.add(path);
                         newFiles++;
                     }
                 }
@@ -161,7 +239,7 @@ public class GitPullActivity extends AppCompatActivity {
         return newFiles;
     }
 
-    void AskForConflicts(final GitLocal localVersion, final HashMap<String, GitObject.GitBlob> conflicts, final HashMap<String, GitObject.GitBlob> filesToPull, final Set<String> filesToPush) {
+    private void AskForConflicts(final GitLocal localVersion, final GitInterface gitInterface, final GitCommit headCommit, final Status status) {
         runOnUiThread(() -> {
             AlertPrompt pt = AlertPromptGenerator.StaticMake(GitPullActivity.this)
                     .setCancelable(true)
@@ -169,19 +247,19 @@ public class GitPullActivity extends AppCompatActivity {
                     .setPositiveButton(R.string.ok, (dialogInterface, v) -> {
                         ConflictView.ConflictViewResult viewResult = ((ConflictView) v).GetResult();
                         for (String s: viewResult.fUseTheir) {
-                            filesToPull.put(s, conflicts.get(s));
+                            status.filesToPull.put(s, status.conflictingFiles.get(s));
                         }
-                        filesToPush.addAll(viewResult.fUseMine);
-                        SyncFiles(localVersion, filesToPull, filesToPush);
+                        status.filesToPush.addAll(viewResult.fUseMine);
+                        SyncFiles(localVersion, gitInterface, headCommit, status);
                     })
                     .setTitle(R.string.conflictingFiles);
-            ConflictView view = new ConflictView(GitPullActivity.this, pt, conflicts.keySet());
+            ConflictView view = new ConflictView(GitPullActivity.this, pt, status.conflictingFiles.keySet());
             pt.setView(view).show();
             view.UpdateButtonState();
         });
     }
 
-    void RmEmptyDirs(File dir, boolean isRoot) {
+    private void RmEmptyDirs(File dir, boolean isRoot) {
         File[] content = dir.listFiles();
 
         if (null == content || content.length == 0) {
@@ -194,7 +272,7 @@ public class GitPullActivity extends AppCompatActivity {
                 RmEmptyDirs(i, false);
     }
 
-    void FinishLoading() {
+    private void FinishLoading() {
         ProgressBar pg = findViewById(R.id.progressBar);
         pg.setIndeterminate(false);
         pg.setMax(1);
@@ -203,7 +281,7 @@ public class GitPullActivity extends AppCompatActivity {
         findViewById(R.id.close_bt).setEnabled(true);
     }
 
-    void SyncFiles(final GitLocal localVersion, final HashMap<String, GitObject.GitBlob> filesToPull, final Set<String> filesToPush) {
+    private void SyncFiles(final GitLocal localVersion, final GitInterface gitInterface, final GitCommit headCommit, final Status status) {
         final OnStreamResponseListener<Void> allDone = new OnStreamResponseListener<Void>() {
             @Override
             public void OnResponse(Void result) {
@@ -225,21 +303,21 @@ public class GitPullActivity extends AppCompatActivity {
         };
 
         final Runnable afterFetching = () -> {
-            if (filesToPush.size() > 0) {
+            if (status.filesToPush.size() > 0) {
                 GitPullActivity.this.OnMsg("Updating remote repository");
-                PushBlobs(filesToPush, localVersion, allDone);
+                PushBlobs(gitInterface, headCommit, status.filesToPush, localVersion, allDone);
             } else {
                 GitPullActivity.this.OnMsg("Nothing to push");
                 allDone.OnResponse(null);
             }
         };
 
-        if (filesToPull.isEmpty()) {
+        if (status.filesToPull.isEmpty()) {
             OnMsg("Nothing to pull");
             afterFetching.run();
         } else {
             OnMsg("Updating local repository");
-            DownloadBlobs(filesToPull, localVersion, new OnStreamResponseListener<Void>() {
+            DownloadBlobs(gitInterface, status.filesToPull, localVersion, new OnStreamResponseListener<Void>() {
                 @Override
                 public void OnResponse(Void result) {
                     afterFetching.run();
@@ -258,7 +336,7 @@ public class GitPullActivity extends AppCompatActivity {
         }
     }
 
-    void DownloadBlobs(Map<String, GitObject.GitBlob> blobs, final GitLocal localVersion, final OnStreamResponseListener<Void> resp) {
+    private void DownloadBlobs(GitInterface gitInterface, Map<String, GitObject.GitBlob> blobs, final GitLocal localVersion, final OnStreamResponseListener<Void> resp) {
         if (blobs.size() == 0) {
             resp.OnResponse(null);
             return;
@@ -280,7 +358,7 @@ public class GitPullActivity extends AppCompatActivity {
                     WriteFile(filename, localVersion, blob, result);
                     logView.append("Done fetching " +files.peek().getValue().GetFilename() +"\n");
                     files.pop();
-                    DownloadNext(files, localVersion, _this, resp);
+                    DownloadNext(gitInterface, files, localVersion, _this, resp);
                 });
             }
 
@@ -292,7 +370,7 @@ public class GitPullActivity extends AppCompatActivity {
 
                 files.pop();
                 if (!files.empty()) {
-                    fGitInterface.FetchBlob(files.peek().getValue(), this);
+                    gitInterface.FetchBlob(files.peek().getValue(), this);
                 } else {
                     resp.OnResponse(null);
                 }
@@ -304,27 +382,27 @@ public class GitPullActivity extends AppCompatActivity {
             }
         };
 
-        DownloadNext(files, localVersion, downloader, resp);
+        DownloadNext(gitInterface, files, localVersion, downloader, resp);
     }
 
-    void DownloadNext(Stack<Map.Entry<String, GitObject.GitBlob>> files, GitLocal localCache, OnStreamResponseListener<byte[]> downloader, OnResponseListener<Void> resp) {
+    private void DownloadNext(GitInterface gitInterface, Stack<Map.Entry<String, GitObject.GitBlob>> files, GitLocal localCache, OnStreamResponseListener<byte[]> downloader, OnResponseListener<Void> resp) {
         if (!files.empty()) {
             if (files.peek().getValue() == null) {
                 // remove file
                 String filename = files.pop().getKey();
                 FileUtils.TrashFile(new File(PathUtils.GetPassDir(this) +filename));
                 localCache.remove(filename);
-                DownloadNext(files, localCache, downloader, resp);
+                DownloadNext(gitInterface, files, localCache, downloader, resp);
                 log.info("Removed file " +filename);
             } else {
-                fGitInterface.FetchBlob(files.peek().getValue(), downloader);
+                gitInterface.FetchBlob(files.peek().getValue(), downloader);
             }
         } else {
             resp.OnResponse(null);
         }
     }
 
-    void WriteFile(String filename, final GitLocal localVersion, GitObject.GitBlob blob, byte[] result) {
+    private void WriteFile(String filename, final GitLocal localVersion, GitObject.GitBlob blob, byte[] result) {
         File f = new File(PathUtils.GetPassDir(this) +filename);
         FileUtils.MkDir(f.getParentFile(), true);
         final int chunkSize = 1024;
@@ -343,16 +421,16 @@ public class GitPullActivity extends AppCompatActivity {
         localVersion.SetHash(filename, GitSha1.BytesToString(blob.GetHash()));
     }
 
-    void PushBlobs(final Set<String> files, final GitLocal localVersion, final OnStreamResponseListener<Void> resp) {
+    private void PushBlobs(final GitInterface gitInterface, final GitCommit headCommit, final Set<String> files, final GitLocal localVersion, final OnStreamResponseListener<Void> resp) {
         if (files.isEmpty()) {
             resp.OnMsg("Nothing to commit");
             resp.OnResponse(null);
         } else {
-            SettingsManager.Git config = (SettingsManager.Git) SettingsManager.GetVCS(this);
-            final GitCommit.Builder commit = new GitCommit.Builder(fHeadCommit, config.GetUsername(), config.GetUserEmail(), COMMIT_MSG);
+            SettingsManager.Git config = (SettingsManager.Git) GetVCS(this);
+            final GitCommit.Builder commit = new GitCommit.Builder(headCommit, config.GetUsername(), config.GetUserEmail(), COMMIT_MSG);
             for (String i : files)
                 commit.AddFile(i, new File(PathUtils.GetPassDir(this) + i));
-            fGitInterface.PushCommitBuilder(commit, new OnStreamResponseListener<Void>() {
+            gitInterface.PushCommitBuilder(commit, new OnStreamResponseListener<Void>() {
                 @Override
                 public void OnMsg(String message) {
                     resp.OnMsg(message);

+ 1 - 1
app/src/main/java/info/knacki/pass/ui/MainActivity.java

@@ -132,7 +132,7 @@ public class MainActivity extends AppCompatActivity implements PasswordEditListe
             case 0:
                 break;
             case R.id.id_sync:
-                startActivity(new Intent(this, GitPullActivity.class));
+                GitPullActivity.StartSyncActivity(this);
                 break;
             case R.id.new_folder:
                 CreateNewFolder();