aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/com/zeapo/pwdstore/git/ResetToRemoteOperation.kt
blob: 60a9fbf3b2bfad73c9c1b5fe196818754547518c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
 * Copyright © 2014-2020 The Android Password Store Authors. All Rights Reserved.
 * SPDX-License-Identifier: GPL-3.0-only
 */
package com.zeapo.pwdstore.git

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.zeapo.pwdstore.R
import com.zeapo.pwdstore.utils.PreferenceKeys
import java.io.File
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.api.GitCommand
import org.eclipse.jgit.api.ResetCommand
import org.eclipse.jgit.api.TransportCommand

/**
 * Creates a new git operation
 *
 * @param fileDir the git working tree directory
 * @param callingActivity the calling activity
 */
class ResetToRemoteOperation(fileDir: File, callingActivity: AppCompatActivity) : GitOperation(fileDir, callingActivity) {

    private lateinit var commands: List<GitCommand<out Any>>

    /**
     * Sets the command
     *
     * @return the current object
     */
    fun setCommands(): ResetToRemoteOperation {
        val remoteBranch = PreferenceManager
            .getDefaultSharedPreferences(callingActivity.applicationContext)
            .getString(PreferenceKeys.GIT_BRANCH_NAME, "master")
        val git = Git(repository)
        val cmds = arrayListOf(
            git.add().addFilepattern("."),
            git.fetch().setRemote("origin"),
            git.reset().setRef("origin/$remoteBranch").setMode(ResetCommand.ResetType.HARD)
        )
        if (git.branchList().call().none { it.name == remoteBranch }) {
            cmds.add(
                git.branchCreate().setName(remoteBranch).setForce(true)
            )
        }
        commands = cmds
        return this
    }

    override fun execute() {
        commands.filterIsInstance<TransportCommand<*, *>>().map { it.setCredentialsProvider(provider) }
        GitAsyncTask(callingActivity, this, Intent()).execute(*commands.toTypedArray())
    }

    override fun onError(err: Exception) {
        super.onError(err)
        MaterialAlertDialogBuilder(callingActivity)
            .setTitle(callingActivity.resources.getString(R.string.jgit_error_dialog_title))
            .setMessage("Error occurred during the sync operation, " +
                "\nPlease check the FAQ for possible reasons why this error might occur." +
                callingActivity.resources.getString(R.string.jgit_error_dialog_text) +
                err)
            .setPositiveButton(callingActivity.resources.getString(R.string.dialog_ok)) { _, _ -> }
            .show()
    }
}