2018-08-12 11:31:27 +02:00
package commands
import (
"fmt"
2019-02-19 14:36:29 +02:00
"io/ioutil"
2018-08-12 11:31:27 +02:00
"os"
2018-08-12 12:22:20 +02:00
"os/exec"
2019-11-05 03:42:07 +02:00
"path/filepath"
2019-11-17 03:07:36 +02:00
"regexp"
2020-03-01 12:00:44 +02:00
"strconv"
2018-08-12 11:50:55 +02:00
"strings"
2019-11-05 03:42:07 +02:00
"time"
2018-08-12 11:31:27 +02:00
2019-02-18 12:29:43 +02:00
"github.com/mgutz/str"
2019-02-11 12:30:27 +02:00
"github.com/go-errors/errors"
2020-03-27 09:00:13 +02:00
gogit "github.com/go-git/go-git/v5"
2020-09-29 11:10:57 +02:00
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
2020-08-15 03:18:40 +02:00
"github.com/jesseduffield/lazygit/pkg/commands/patch"
2019-02-18 12:29:43 +02:00
"github.com/jesseduffield/lazygit/pkg/config"
2020-09-27 08:17:26 +02:00
"github.com/jesseduffield/lazygit/pkg/env"
2018-08-28 10:01:53 +02:00
"github.com/jesseduffield/lazygit/pkg/i18n"
2020-09-29 10:34:01 +02:00
"github.com/jesseduffield/lazygit/pkg/models"
2018-08-12 13:04:47 +02:00
"github.com/jesseduffield/lazygit/pkg/utils"
2018-08-25 00:51:47 +02:00
"github.com/sirupsen/logrus"
2018-08-12 11:50:55 +02:00
gitconfig "github.com/tcnksm/go-gitconfig"
2018-08-12 11:31:27 +02:00
)
2019-11-17 03:07:36 +02:00
// this takes something like:
// * (HEAD detached at 264fc6f5)
// remotes
// and returns '264fc6f5' as the second match
const CurrentBranchNameRegex = ` (?m)^\*.*?([^ ]*?)\)?$ `
2019-11-21 12:09:14 +02:00
func verifyInGitRepo ( runCmd func ( string , ... interface { } ) error ) error {
2018-09-04 06:16:19 +02:00
return runCmd ( "git status" )
2018-08-29 22:55:57 +02:00
}
2018-09-02 17:15:27 +02:00
func navigateToRepoRootDirectory ( stat func ( string ) ( os . FileInfo , error ) , chdir func ( string ) error ) error {
2020-09-27 08:17:26 +02:00
gitDir := env . GetGitDirEnv ( )
if gitDir != "" {
2020-09-27 07:36:04 +02:00
// we've been given the git directory explicitly so no need to navigate to it
2020-09-27 08:17:26 +02:00
_ , err := stat ( gitDir )
2020-09-27 07:36:04 +02:00
if err != nil {
2020-09-29 11:10:57 +02:00
return utils . WrapError ( err )
2020-09-27 07:36:04 +02:00
}
return nil
}
2020-09-27 08:17:26 +02:00
// we haven't been given the git dir explicitly so we assume it's in the current working directory as `.git/` (or an ancestor directory)
2018-08-29 22:55:57 +02:00
for {
2019-05-12 09:04:32 +02:00
_ , err := stat ( ".git" )
2018-08-29 22:55:57 +02:00
2019-05-03 09:02:57 +02:00
if err == nil {
2019-05-12 09:04:32 +02:00
return nil
2018-08-29 22:55:57 +02:00
}
2018-09-02 17:15:27 +02:00
if ! os . IsNotExist ( err ) {
2020-09-29 11:10:57 +02:00
return utils . WrapError ( err )
2018-09-02 17:15:27 +02:00
}
2018-08-29 22:55:57 +02:00
2018-09-02 17:15:27 +02:00
if err = chdir ( ".." ) ; err != nil {
2020-09-29 11:10:57 +02:00
return utils . WrapError ( err )
2018-08-29 22:55:57 +02:00
}
}
}
2020-09-27 11:39:13 +02:00
// resolvePath takes a path containing a symlink and returns the true path
func resolvePath ( path string ) ( string , error ) {
l , err := os . Lstat ( path )
if err != nil {
return "" , err
}
if l . Mode ( ) & os . ModeSymlink == 0 {
return path , nil
}
return filepath . EvalSymlinks ( path )
}
2020-09-27 07:36:04 +02:00
func setupRepository ( openGitRepository func ( string ) ( * gogit . Repository , error ) , sLocalize func ( string ) string ) ( * gogit . Repository , error ) {
2020-09-27 11:39:13 +02:00
unresolvedPath := env . GetGitDirEnv ( )
if unresolvedPath == "" {
var err error
unresolvedPath , err = os . Getwd ( )
if err != nil {
return nil , err
}
}
path , err := resolvePath ( unresolvedPath )
if err != nil {
return nil , err
2020-09-27 07:36:04 +02:00
}
repository , err := openGitRepository ( path )
2018-09-02 17:15:27 +02:00
if err != nil {
if strings . Contains ( err . Error ( ) , ` unquoted '\' must be followed by new line ` ) {
2020-09-27 07:36:04 +02:00
return nil , errors . New ( sLocalize ( "GitconfigParseErr" ) )
2018-09-02 17:15:27 +02:00
}
2018-08-29 22:55:57 +02:00
2020-09-27 07:36:04 +02:00
return nil , err
2018-08-29 22:55:57 +02:00
}
2020-09-27 07:36:04 +02:00
return repository , err
2018-08-29 22:55:57 +02:00
}
2018-09-02 17:15:27 +02:00
// GitCommand is our main git interface
type GitCommand struct {
2019-11-04 10:47:25 +02:00
Log * logrus . Entry
2020-09-29 11:10:57 +02:00
OSCommand * oscommands . OSCommand
2019-11-04 10:47:25 +02:00
Repo * gogit . Repository
Tr * i18n . Localizer
Config config . AppConfigurer
getGlobalGitConfig func ( string ) ( string , error )
getLocalGitConfig func ( string ) ( string , error )
removeFile func ( string ) error
DotGitDir string
onSuccessfulContinue func ( ) error
2020-08-15 03:18:40 +02:00
PatchManager * patch . PatchManager
2020-05-15 13:26:02 +02:00
// Push to current determines whether the user has configured to push to the remote branch of the same name as the current or not
PushToCurrent bool
2018-09-02 17:15:27 +02:00
}
// NewGitCommand it runs git commands
2020-09-29 11:10:57 +02:00
func NewGitCommand ( log * logrus . Entry , osCommand * oscommands . OSCommand , tr * i18n . Localizer , config config . AppConfigurer ) ( * GitCommand , error ) {
2018-09-02 17:15:27 +02:00
var repo * gogit . Repository
2020-05-15 13:26:02 +02:00
// see what our default push behaviour is
output , err := osCommand . RunCommandWithOutput ( "git config --get push.default" )
pushToCurrent := false
if err != nil {
log . Errorf ( "error reading git config: %v" , err )
} else {
pushToCurrent = strings . TrimSpace ( output ) == "current"
}
2020-09-27 07:36:04 +02:00
if err := verifyInGitRepo ( osCommand . RunCommand ) ; err != nil {
return nil , err
2018-09-02 17:15:27 +02:00
}
2020-09-27 07:36:04 +02:00
if err := navigateToRepoRootDirectory ( os . Stat , os . Chdir ) ; err != nil {
return nil , err
}
if repo , err = setupRepository ( gogit . PlainOpen , tr . SLocalize ) ; err != nil {
return nil , err
2018-09-02 17:15:27 +02:00
}
2019-05-12 09:04:32 +02:00
dotGitDir , err := findDotGitDir ( os . Stat , ioutil . ReadFile )
if err != nil {
return nil , err
}
2019-11-05 09:10:47 +02:00
gitCommand := & GitCommand {
2018-09-10 21:57:08 +02:00
Log : log ,
OSCommand : osCommand ,
Tr : tr ,
Repo : repo ,
2019-02-18 12:29:43 +02:00
Config : config ,
2018-09-10 21:57:08 +02:00
getGlobalGitConfig : gitconfig . Global ,
getLocalGitConfig : gitconfig . Local ,
2018-09-20 01:48:56 +02:00
removeFile : os . RemoveAll ,
2019-05-12 09:04:32 +02:00
DotGitDir : dotGitDir ,
2020-05-15 13:26:02 +02:00
PushToCurrent : pushToCurrent ,
2019-11-05 09:10:47 +02:00
}
2020-08-22 10:29:09 +02:00
gitCommand . PatchManager = patch . NewPatchManager ( log , gitCommand . ApplyPatch , gitCommand . ShowFileDiff )
2019-11-05 09:10:47 +02:00
return gitCommand , nil
2018-09-02 17:15:27 +02:00
}
2019-05-12 09:04:32 +02:00
func findDotGitDir ( stat func ( string ) ( os . FileInfo , error ) , readFile func ( filename string ) ( [ ] byte , error ) ) ( string , error ) {
2020-09-27 08:17:26 +02:00
if env . GetGitDirEnv ( ) != "" {
return env . GetGitDirEnv ( ) , nil
2020-09-27 07:36:04 +02:00
}
2019-05-12 09:04:32 +02:00
f , err := stat ( ".git" )
if err != nil {
return "" , err
}
if f . IsDir ( ) {
return ".git" , nil
}
fileBytes , err := readFile ( ".git" )
if err != nil {
return "" , err
}
fileContent := string ( fileBytes )
if ! strings . HasPrefix ( fileContent , "gitdir: " ) {
return "" , errors . New ( ".git is a file which suggests we are in a submodule but the file's contents do not contain a gitdir pointing to the actual .git directory" )
}
return strings . TrimSpace ( strings . TrimPrefix ( fileContent , "gitdir: " ) ) , nil
}
2018-08-12 12:22:20 +02:00
// GetStashEntryDiff stash diff
allow fast flicking through any list panel
Up till now our approach to rendering things like file diffs, branch logs, and
commit patches, has been to run a command on the command line, wait for it to
complete, take its output as a string, and then write that string to the main
view (or secondary view e.g. when showing both staged and unstaged changes of a
file).
This has caused various issues. For once, if you are flicking through a list of
files and an untracked file is particularly large, not only will this require
lazygit to load that whole file into memory (or more accurately it's equally
large diff), it also will slow down the UI thread while loading that file, and
if the user continued down the list, the original command might eventually
resolve and replace whatever the diff is for the newly selected file.
Following what we've done in lazydocker, I've added a tasks package for when you
need something done but you want it to cancel as soon as something newer comes
up. Given this typically involves running a command to display to a view, I've
added a viewBufferManagerMap struct to the Gui struct which allows you to define
these tasks on a per-view basis.
viewBufferManagers can run files and directly write the output to their view,
meaning we no longer need to use so much memory.
In the tasks package there is a helper method called NewCmdTask which takes a
command, an initial amount of lines to read, and then runs that command, reads
that number of lines, and allows for a readLines channel to tell it to read more
lines. We read more lines when we scroll or resize the window.
There is an adapter for the tasks package in a file called tasks_adapter which
wraps the functions from the tasks package in gui-specific stuff like clearing
the main view before starting the next task that wants to write to the main
view.
I've removed some small features as part of this work, namely the little headers
that were at the top of the main view for some situations. For example, we no
longer show the upstream of a selected branch. I want to re-introduce this in
the future, but I didn't want to make this tasks system too complicated, and in
order to facilitate a header section in the main view we'd need to have a task
that gets the upstream for the current branch, writes it to the header, then
tells another task to write the branch log to the main view, but without
clearing inbetween. So it would get messy. I'm thinking instead of having a
separate 'header' view atop the main view to render that kind of thing (which
can happen in another PR)
I've also simplified the 'git show' to just call 'git show' and not do anything
fancy when it comes to merge commits.
I considered using this tasks approach whenever we write to a view. The only
thing is that the renderString method currently resets the origin of a view and
I don't want to lose that. So I've left some in there that I consider harmless,
but we should probably be just using tasks now for all rendering, even if it's
just strings we can instantly make.
2020-01-11 05:54:59 +02:00
func ( c * GitCommand ) ShowStashEntryCmdStr ( index int ) string {
2020-08-23 07:01:02 +02:00
return fmt . Sprintf ( "git stash show -p --stat --color=%s stash@{%d}" , c . colorArg ( ) , index )
2018-08-12 12:22:20 +02:00
}
// GetStatusFiles git status files
2020-08-07 09:52:17 +02:00
type GetStatusFileOptions struct {
NoRenames bool
}
2020-09-27 07:36:04 +02:00
func ( c * GitCommand ) GetConfigValue ( key string ) string {
output , _ := c . OSCommand . RunCommandWithOutput ( "git config --get %s" , key )
// looks like this returns an error if there is no matching value which we're okay with
return strings . TrimSpace ( output )
}
2018-08-12 12:22:20 +02:00
// StashDo modify stash
2018-08-14 09:47:33 +02:00
func ( c * GitCommand ) StashDo ( index int , method string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git stash %s stash@{%d}" , method , index )
2018-08-12 12:22:20 +02:00
}
// StashSave save stash
2018-08-14 09:47:33 +02:00
// TODO: before calling this, check if there is anything to save
func ( c * GitCommand ) StashSave ( message string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git stash save %s" , c . OSCommand . Quote ( message ) )
2018-08-12 12:22:20 +02:00
}
2018-09-12 10:24:03 +02:00
func includesInt ( list [ ] int , a int ) bool {
for _ , b := range list {
if b == a {
return true
}
}
return false
2018-08-12 12:22:20 +02:00
}
2018-12-05 11:06:47 +02:00
// ResetAndClean removes all unstaged changes and removes all untracked files
func ( c * GitCommand ) ResetAndClean ( ) error {
2020-09-29 00:47:14 +02:00
submoduleConfigs , err := c . GetSubmoduleConfigs ( )
if err != nil {
return err
}
if len ( submoduleConfigs ) > 0 {
for _ , config := range submoduleConfigs {
if err := c . SubmoduleStash ( config ) ; err != nil {
return err
}
}
if err := c . SubmoduleUpdateAll ( ) ; err != nil {
return err
}
}
2020-01-07 11:12:36 +02:00
if err := c . ResetHard ( "HEAD" ) ; err != nil {
2018-12-05 11:06:47 +02:00
return err
}
2019-03-18 12:19:07 +02:00
return c . RemoveUntrackedFiles ( )
2018-08-12 11:50:55 +02:00
}
2018-12-07 09:52:31 +02:00
func ( c * GitCommand ) GetCurrentBranchUpstreamDifferenceCount ( ) ( string , string ) {
2019-11-17 05:28:38 +02:00
return c . GetCommitDifferences ( "HEAD" , "HEAD@{u}" )
2018-12-07 09:52:31 +02:00
}
func ( c * GitCommand ) GetBranchUpstreamDifferenceCount ( branchName string ) ( string , string ) {
2019-11-17 05:28:38 +02:00
return c . GetCommitDifferences ( branchName , branchName + "@{u}" )
2018-12-07 09:52:31 +02:00
}
// GetCommitDifferences checks how many pushables/pullables there are for the
2018-08-12 11:50:55 +02:00
// current branch
2018-12-07 09:52:31 +02:00
func ( c * GitCommand ) GetCommitDifferences ( from , to string ) ( string , string ) {
command := "git rev-list %s..%s --count"
2019-11-21 12:09:14 +02:00
pushableCount , err := c . OSCommand . RunCommandWithOutput ( command , to , from )
2018-08-12 11:50:55 +02:00
if err != nil {
return "?" , "?"
}
2019-11-21 12:09:14 +02:00
pullableCount , err := c . OSCommand . RunCommandWithOutput ( command , from , to )
2018-08-12 11:50:55 +02:00
if err != nil {
return "?" , "?"
}
return strings . TrimSpace ( pushableCount ) , strings . TrimSpace ( pullableCount )
}
// RenameCommit renames the topmost commit with the given name
2018-08-14 09:47:33 +02:00
func ( c * GitCommand ) RenameCommit ( name string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git commit --allow-empty --amend -m %s" , c . OSCommand . Quote ( name ) )
2018-08-12 11:50:55 +02:00
}
2019-02-24 00:42:24 +02:00
// RebaseBranch interactive rebases onto a branch
func ( c * GitCommand ) RebaseBranch ( branchName string ) error {
cmd , err := c . PrepareInteractiveRebaseCommand ( branchName , "" , false )
2018-11-29 18:57:28 +02:00
if err != nil {
return err
}
2019-02-24 00:42:24 +02:00
return c . OSCommand . RunPreparedCommand ( cmd )
2018-11-29 18:57:28 +02:00
}
2020-08-11 13:18:38 +02:00
type FetchOptions struct {
PromptUserForCredential func ( string ) string
RemoteName string
BranchName string
}
2018-08-12 12:22:20 +02:00
// Fetch fetch git repo
2020-08-11 13:18:38 +02:00
func ( c * GitCommand ) Fetch ( opts FetchOptions ) error {
command := "git fetch"
if opts . RemoteName != "" {
command = fmt . Sprintf ( "%s %s" , command , opts . RemoteName )
}
if opts . BranchName != "" {
command = fmt . Sprintf ( "%s %s" , command , opts . BranchName )
}
return c . OSCommand . DetectUnamePass ( command , func ( question string ) string {
if opts . PromptUserForCredential != nil {
return opts . PromptUserForCredential ( question )
2018-11-25 14:15:36 +02:00
}
2018-12-18 13:23:17 +02:00
return "\n"
2018-11-25 14:15:36 +02:00
} )
2018-08-12 11:50:55 +02:00
}
2018-08-12 12:22:20 +02:00
// ResetToCommit reset to commit
2020-09-29 11:10:57 +02:00
func ( c * GitCommand ) ResetToCommit ( sha string , strength string , options oscommands . RunCommandOptions ) error {
2020-03-21 09:27:20 +02:00
return c . OSCommand . RunCommandWithOptions ( fmt . Sprintf ( "git reset --%s %s" , strength , sha ) , options )
2018-08-12 11:50:55 +02:00
}
2018-08-12 12:22:20 +02:00
// NewBranch create new branch
2020-08-16 14:01:14 +02:00
func ( c * GitCommand ) NewBranch ( name string , base string ) error {
return c . OSCommand . RunCommand ( "git checkout -b %s %s" , name , base )
2018-08-12 11:50:55 +02:00
}
2020-03-26 11:29:35 +02:00
// CurrentBranchName get the current branch name and displayname.
// the first returned string is the name and the second is the displayname
// e.g. name is 123asdf and displayname is '(HEAD detached at 123asdf)'
func ( c * GitCommand ) CurrentBranchName ( ) ( string , string , error ) {
2018-11-14 10:08:42 +02:00
branchName , err := c . OSCommand . RunCommandWithOutput ( "git symbolic-ref --short HEAD" )
2020-03-26 11:29:35 +02:00
if err == nil && branchName != "HEAD\n" {
trimmedBranchName := strings . TrimSpace ( branchName )
return trimmedBranchName , trimmedBranchName , nil
}
output , err := c . OSCommand . RunCommandWithOutput ( "git branch --contains" )
if err != nil {
return "" , "" , err
}
for _ , line := range utils . SplitLines ( output ) {
2019-11-21 12:45:18 +02:00
re := regexp . MustCompile ( CurrentBranchNameRegex )
2020-03-26 11:29:35 +02:00
match := re . FindStringSubmatch ( line )
if len ( match ) > 0 {
branchName = match [ 1 ]
displayBranchName := match [ 0 ] [ 2 : ]
return branchName , displayBranchName , nil
}
2018-09-25 12:31:19 +02:00
}
2020-03-26 11:29:35 +02:00
return "HEAD" , "HEAD" , nil
2018-09-25 12:11:33 +02:00
}
2018-08-12 12:22:20 +02:00
// DeleteBranch delete branch
2018-08-15 15:02:01 +02:00
func ( c * GitCommand ) DeleteBranch ( branch string , force bool ) error {
2018-09-06 23:38:49 +02:00
command := "git branch -d"
2018-08-15 15:02:01 +02:00
if force {
2018-09-06 23:38:49 +02:00
command = "git branch -D"
2018-08-15 15:02:01 +02:00
}
2018-09-06 23:38:49 +02:00
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "%s %s" , command , branch )
2018-08-12 11:50:55 +02:00
}
2020-08-11 13:18:38 +02:00
type MergeOpts struct {
FastForwardOnly bool
}
2018-08-12 12:22:20 +02:00
// Merge merge
2020-08-11 13:18:38 +02:00
func ( c * GitCommand ) Merge ( branchName string , opts MergeOpts ) error {
2020-04-20 10:35:22 +02:00
mergeArgs := c . Config . GetUserConfig ( ) . GetString ( "git.merging.args" )
2020-08-11 13:18:38 +02:00
command := fmt . Sprintf ( "git merge --no-edit %s %s" , mergeArgs , branchName )
if opts . FastForwardOnly {
command = fmt . Sprintf ( "%s --ff-only" , command )
}
return c . OSCommand . RunCommand ( command )
2018-08-12 11:50:55 +02:00
}
2018-08-12 12:22:20 +02:00
// AbortMerge abort merge
2018-08-14 09:47:33 +02:00
func ( c * GitCommand ) AbortMerge ( ) error {
return c . OSCommand . RunCommand ( "git merge --abort" )
2018-08-12 12:22:20 +02:00
}
2018-09-10 21:57:08 +02:00
// usingGpg tells us whether the user has gpg enabled so that we can know
2018-08-14 00:33:27 +02:00
// whether we need to run a subprocess to allow them to enter their password
2018-09-10 21:57:08 +02:00
func ( c * GitCommand ) usingGpg ( ) bool {
2020-05-30 23:39:07 +02:00
overrideGpg := c . Config . GetUserConfig ( ) . GetBool ( "git.overrideGpg" )
if overrideGpg {
return false
}
2018-09-12 07:50:49 +02:00
gpgsign , _ := c . getLocalGitConfig ( "commit.gpgsign" )
2018-08-14 00:33:27 +02:00
if gpgsign == "" {
2018-09-12 07:50:49 +02:00
gpgsign , _ = c . getGlobalGitConfig ( "commit.gpgsign" )
2018-08-14 00:33:27 +02:00
}
2018-09-10 21:57:08 +02:00
value := strings . ToLower ( gpgsign )
return value == "true" || value == "1" || value == "yes" || value == "on"
2018-08-14 00:33:27 +02:00
}
2018-09-10 22:01:52 +02:00
// Commit commits to git
2019-04-13 05:34:12 +02:00
func ( c * GitCommand ) Commit ( message string , flags string ) ( * exec . Cmd , error ) {
2020-07-14 21:43:12 +02:00
command := fmt . Sprintf ( "git commit %s -m %s" , flags , strconv . Quote ( message ) )
2019-02-24 00:42:24 +02:00
if c . usingGpg ( ) {
2020-07-13 16:00:00 +02:00
return c . OSCommand . ShellCommandFromString ( command ) , nil
2018-09-12 15:20:35 +02:00
}
2019-02-24 00:42:24 +02:00
return nil , c . OSCommand . RunCommand ( command )
}
2020-04-27 18:31:22 +02:00
// Get the subject of the HEAD commit
func ( c * GitCommand ) GetHeadCommitMessage ( ) ( string , error ) {
cmdStr := "git log -1 --pretty=%s"
message , err := c . OSCommand . RunCommandWithOutput ( cmdStr )
return strings . TrimSpace ( message ) , err
}
2020-08-16 11:31:55 +02:00
func ( c * GitCommand ) GetCommitMessage ( commitSha string ) ( string , error ) {
cmdStr := "git rev-list --format=%B --max-count=1 " + commitSha
messageWithHeader , err := c . OSCommand . RunCommandWithOutput ( cmdStr )
message := strings . Join ( strings . SplitAfter ( messageWithHeader , "\n" ) [ 1 : ] , "\n" )
return strings . TrimSpace ( message ) , err
}
2019-02-24 00:42:24 +02:00
// AmendHead amends HEAD with whatever is staged in your working tree
func ( c * GitCommand ) AmendHead ( ) ( * exec . Cmd , error ) {
2019-11-04 10:47:25 +02:00
command := "git commit --amend --no-edit --allow-empty"
2018-09-10 21:57:08 +02:00
if c . usingGpg ( ) {
2020-07-13 16:00:00 +02:00
return c . OSCommand . ShellCommandFromString ( command ) , nil
2018-08-12 11:50:55 +02:00
}
2018-09-10 22:25:02 +02:00
2018-08-14 09:47:33 +02:00
return nil , c . OSCommand . RunCommand ( command )
2018-08-12 11:50:55 +02:00
}
2018-09-10 22:38:08 +02:00
// Push pushes to a branch
2020-08-11 12:29:05 +02:00
func ( c * GitCommand ) Push ( branchName string , force bool , upstream string , args string , promptUserForCredential func ( string ) string ) error {
2018-08-19 13:28:13 +02:00
forceFlag := ""
if force {
2019-11-11 14:22:09 +02:00
forceFlag = "--force-with-lease"
2018-08-19 13:28:13 +02:00
}
2018-09-10 22:38:08 +02:00
2019-11-11 14:22:09 +02:00
setUpstreamArg := ""
if upstream != "" {
setUpstreamArg = "--set-upstream " + upstream
}
2020-01-28 11:35:23 +02:00
cmd := fmt . Sprintf ( "git push --follow-tags %s %s %s" , forceFlag , setUpstreamArg , args )
2020-08-11 12:29:05 +02:00
return c . OSCommand . DetectUnamePass ( cmd , promptUserForCredential )
2018-08-12 11:50:55 +02:00
}
2018-09-12 22:28:49 +02:00
// CatFile obtains the content of a file
2018-08-19 12:13:29 +02:00
func ( c * GitCommand ) CatFile ( fileName string ) ( string , error ) {
2020-09-29 11:10:57 +02:00
return c . OSCommand . RunCommandWithOutput ( "%s %s" , c . OSCommand . Platform . CatCmd , c . OSCommand . Quote ( fileName ) )
2018-08-12 12:22:20 +02:00
}
// StageFile stages a file
2018-08-19 12:13:29 +02:00
func ( c * GitCommand ) StageFile ( fileName string ) error {
2020-07-19 04:19:50 +02:00
// renamed files look like "file1 -> file2"
fileNames := strings . Split ( fileName , " -> " )
return c . OSCommand . RunCommand ( "git add %s" , c . OSCommand . Quote ( fileNames [ len ( fileNames ) - 1 ] ) )
2018-08-12 12:22:20 +02:00
}
2018-08-25 00:51:47 +02:00
// StageAll stages all files
func ( c * GitCommand ) StageAll ( ) error {
return c . OSCommand . RunCommand ( "git add -A" )
}
// UnstageAll stages all files
func ( c * GitCommand ) UnstageAll ( ) error {
return c . OSCommand . RunCommand ( "git reset" )
}
2018-08-12 12:22:20 +02:00
// UnStageFile unstages a file
2018-08-19 12:13:29 +02:00
func ( c * GitCommand ) UnStageFile ( fileName string , tracked bool ) error {
2018-09-13 21:27:35 +02:00
command := "git rm --cached %s"
2018-08-12 12:22:20 +02:00
if tracked {
2018-09-13 21:27:35 +02:00
command = "git reset HEAD %s"
2018-08-12 12:22:20 +02:00
}
2019-02-20 10:47:01 +02:00
// renamed files look like "file1 -> file2"
fileNames := strings . Split ( fileName , " -> " )
for _ , name := range fileNames {
2019-11-21 12:09:14 +02:00
if err := c . OSCommand . RunCommand ( command , c . OSCommand . Quote ( name ) ) ; err != nil {
2019-02-20 10:47:01 +02:00
return err
}
}
return nil
2018-08-12 12:22:20 +02:00
}
// IsInMergeState states whether we are still mid-merge
func ( c * GitCommand ) IsInMergeState ( ) ( bool , error ) {
2020-09-27 08:17:26 +02:00
return c . OSCommand . FileExists ( filepath . Join ( c . DotGitDir , "MERGE_HEAD" ) )
2018-08-12 12:22:20 +02:00
}
2019-03-02 11:00:26 +02:00
// RebaseMode returns "" for non-rebase mode, "normal" for normal rebase
// and "interactive" for interactive rebase
func ( c * GitCommand ) RebaseMode ( ) ( string , error ) {
2020-09-27 08:17:26 +02:00
exists , err := c . OSCommand . FileExists ( filepath . Join ( c . DotGitDir , "rebase-apply" ) )
2019-03-02 11:00:26 +02:00
if err != nil {
return "" , err
}
if exists {
return "normal" , nil
}
2020-09-27 08:17:26 +02:00
exists , err = c . OSCommand . FileExists ( filepath . Join ( c . DotGitDir , "rebase-merge" ) )
2019-03-02 11:00:26 +02:00
if exists {
return "interactive" , err
} else {
return "" , err
}
2018-12-02 18:33:16 +02:00
}
2020-09-29 10:45:00 +02:00
func ( c * GitCommand ) BeforeAndAfterFileForRename ( file * models . File ) ( * models . File , * models . File , error ) {
2020-08-07 09:52:17 +02:00
if ! file . IsRename ( ) {
return nil , nil , errors . New ( "Expected renamed file" )
}
// we've got a file that represents a rename from one file to another. Unfortunately
// our File abstraction fails to consider this case, so here we will refetch
// all files, passing the --no-renames flag and then recursively call the function
// again for the before file and after file. At some point we should fix the abstraction itself
split := strings . Split ( file . Name , " -> " )
filesWithoutRenames := c . GetStatusFiles ( GetStatusFileOptions { NoRenames : true } )
2020-09-29 10:45:00 +02:00
var beforeFile * models . File
var afterFile * models . File
2020-08-07 09:52:17 +02:00
for _ , f := range filesWithoutRenames {
if f . Name == split [ 0 ] {
beforeFile = f
}
if f . Name == split [ 1 ] {
afterFile = f
}
}
if beforeFile == nil || afterFile == nil {
return nil , nil , errors . New ( "Could not find deleted file or new file for file rename" )
}
if beforeFile . IsRename ( ) || afterFile . IsRename ( ) {
// probably won't happen but we want to ensure we don't get an infinite loop
return nil , nil , errors . New ( "Nested rename found" )
}
return beforeFile , afterFile , nil
}
2019-03-18 11:44:33 +02:00
// DiscardAllFileChanges directly
2020-09-29 10:45:00 +02:00
func ( c * GitCommand ) DiscardAllFileChanges ( file * models . File ) error {
2020-08-07 09:52:17 +02:00
if file . IsRename ( ) {
beforeFile , afterFile , err := c . BeforeAndAfterFileForRename ( file )
if err != nil {
return err
}
if err := c . DiscardAllFileChanges ( beforeFile ) ; err != nil {
return err
}
if err := c . DiscardAllFileChanges ( afterFile ) ; err != nil {
return err
}
return nil
}
2018-08-12 12:22:20 +02:00
// if the file isn't tracked, we assume you want to delete it
2019-02-20 11:01:29 +02:00
quotedFileName := c . OSCommand . Quote ( file . Name )
2020-09-28 01:14:32 +02:00
if file . HasStagedChanges || file . HasMergeConflicts {
2019-11-21 12:09:14 +02:00
if err := c . OSCommand . RunCommand ( "git reset -- %s" , quotedFileName ) ; err != nil {
2018-08-18 12:14:44 +02:00
return err
}
}
2019-07-13 14:57:35 +02:00
2018-08-12 12:22:20 +02:00
if ! file . Tracked {
2018-09-16 22:03:56 +02:00
return c . removeFile ( file . Name )
2018-08-12 12:22:20 +02:00
}
2019-03-18 11:44:33 +02:00
return c . DiscardUnstagedFileChanges ( file )
}
// DiscardUnstagedFileChanges directly
2020-09-29 10:45:00 +02:00
func ( c * GitCommand ) DiscardUnstagedFileChanges ( file * models . File ) error {
2019-03-18 11:44:33 +02:00
quotedFileName := c . OSCommand . Quote ( file . Name )
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git checkout -- %s" , quotedFileName )
2018-08-12 12:22:20 +02:00
}
2020-01-07 11:24:10 +02:00
// Checkout checks out a branch (or commit), with --force if you set the force arg to true
2020-03-21 09:27:20 +02:00
type CheckoutOptions struct {
Force bool
EnvVars [ ] string
}
func ( c * GitCommand ) Checkout ( branch string , options CheckoutOptions ) error {
2018-08-12 12:22:20 +02:00
forceArg := ""
2020-03-21 09:27:20 +02:00
if options . Force {
2018-08-12 12:22:20 +02:00
forceArg = "--force "
}
2020-09-29 11:10:57 +02:00
return c . OSCommand . RunCommandWithOptions ( fmt . Sprintf ( "git checkout %s %s" , forceArg , branch ) , oscommands . RunCommandOptions { EnvVars : options . EnvVars } )
2018-08-12 12:22:20 +02:00
}
2018-08-29 14:27:17 +02:00
// PrepareCommitAmendSubProcess prepares a subprocess for `git commit --amend --allow-empty`
func ( c * GitCommand ) PrepareCommitAmendSubProcess ( ) * exec . Cmd {
return c . OSCommand . PrepareSubProcess ( "git" , "commit" , "--amend" , "--allow-empty" )
}
2018-08-12 12:22:20 +02:00
// GetBranchGraph gets the color-formatted graph of the log for the given branch
// Currently it limits the result to 100 commits, but when we get async stuff
// working we can do lazy loading
func ( c * GitCommand ) GetBranchGraph ( branchName string ) ( string , error ) {
allow fast flicking through any list panel
Up till now our approach to rendering things like file diffs, branch logs, and
commit patches, has been to run a command on the command line, wait for it to
complete, take its output as a string, and then write that string to the main
view (or secondary view e.g. when showing both staged and unstaged changes of a
file).
This has caused various issues. For once, if you are flicking through a list of
files and an untracked file is particularly large, not only will this require
lazygit to load that whole file into memory (or more accurately it's equally
large diff), it also will slow down the UI thread while loading that file, and
if the user continued down the list, the original command might eventually
resolve and replace whatever the diff is for the newly selected file.
Following what we've done in lazydocker, I've added a tasks package for when you
need something done but you want it to cancel as soon as something newer comes
up. Given this typically involves running a command to display to a view, I've
added a viewBufferManagerMap struct to the Gui struct which allows you to define
these tasks on a per-view basis.
viewBufferManagers can run files and directly write the output to their view,
meaning we no longer need to use so much memory.
In the tasks package there is a helper method called NewCmdTask which takes a
command, an initial amount of lines to read, and then runs that command, reads
that number of lines, and allows for a readLines channel to tell it to read more
lines. We read more lines when we scroll or resize the window.
There is an adapter for the tasks package in a file called tasks_adapter which
wraps the functions from the tasks package in gui-specific stuff like clearing
the main view before starting the next task that wants to write to the main
view.
I've removed some small features as part of this work, namely the little headers
that were at the top of the main view for some situations. For example, we no
longer show the upstream of a selected branch. I want to re-introduce this in
the future, but I didn't want to make this tasks system too complicated, and in
order to facilitate a header section in the main view we'd need to have a task
that gets the upstream for the current branch, writes it to the header, then
tells another task to write the branch log to the main view, but without
clearing inbetween. So it would get messy. I'm thinking instead of having a
separate 'header' view atop the main view to render that kind of thing (which
can happen in another PR)
I've also simplified the 'git show' to just call 'git show' and not do anything
fancy when it comes to merge commits.
I considered using this tasks approach whenever we write to a view. The only
thing is that the renderString method currently resets the origin of a view and
I don't want to lose that. So I've left some in there that I consider harmless,
but we should probably be just using tasks now for all rendering, even if it's
just strings we can instantly make.
2020-01-11 05:54:59 +02:00
cmdStr := c . GetBranchGraphCmdStr ( branchName )
return c . OSCommand . RunCommandWithOutput ( cmdStr )
2018-08-12 12:22:20 +02:00
}
2018-08-12 13:04:47 +02:00
2019-11-13 13:14:57 +02:00
func ( c * GitCommand ) GetUpstreamForBranch ( branchName string ) ( string , error ) {
2019-11-21 12:09:14 +02:00
output , err := c . OSCommand . RunCommandWithOutput ( "git rev-parse --abbrev-ref --symbolic-full-name %s@{u}" , branchName )
2019-11-13 13:14:57 +02:00
return strings . TrimSpace ( output ) , err
}
2018-08-12 13:04:47 +02:00
// Ignore adds a file to the gitignore for the repo
2018-08-19 12:41:04 +02:00
func ( c * GitCommand ) Ignore ( filename string ) error {
return c . OSCommand . AppendLineToFile ( ".gitignore" , filename )
2018-08-12 13:04:47 +02:00
}
2020-03-29 01:11:15 +02:00
func ( c * GitCommand ) ShowCmdStr ( sha string , filterPath string ) string {
filterPathArg := ""
if filterPath != "" {
filterPathArg = fmt . Sprintf ( " -- %s" , c . OSCommand . Quote ( filterPath ) )
2020-03-28 07:28:35 +02:00
}
2020-09-28 01:14:32 +02:00
return fmt . Sprintf ( "git show --submodule --color=%s --no-renames --stat -p %s %s" , c . colorArg ( ) , sha , filterPathArg )
allow fast flicking through any list panel
Up till now our approach to rendering things like file diffs, branch logs, and
commit patches, has been to run a command on the command line, wait for it to
complete, take its output as a string, and then write that string to the main
view (or secondary view e.g. when showing both staged and unstaged changes of a
file).
This has caused various issues. For once, if you are flicking through a list of
files and an untracked file is particularly large, not only will this require
lazygit to load that whole file into memory (or more accurately it's equally
large diff), it also will slow down the UI thread while loading that file, and
if the user continued down the list, the original command might eventually
resolve and replace whatever the diff is for the newly selected file.
Following what we've done in lazydocker, I've added a tasks package for when you
need something done but you want it to cancel as soon as something newer comes
up. Given this typically involves running a command to display to a view, I've
added a viewBufferManagerMap struct to the Gui struct which allows you to define
these tasks on a per-view basis.
viewBufferManagers can run files and directly write the output to their view,
meaning we no longer need to use so much memory.
In the tasks package there is a helper method called NewCmdTask which takes a
command, an initial amount of lines to read, and then runs that command, reads
that number of lines, and allows for a readLines channel to tell it to read more
lines. We read more lines when we scroll or resize the window.
There is an adapter for the tasks package in a file called tasks_adapter which
wraps the functions from the tasks package in gui-specific stuff like clearing
the main view before starting the next task that wants to write to the main
view.
I've removed some small features as part of this work, namely the little headers
that were at the top of the main view for some situations. For example, we no
longer show the upstream of a selected branch. I want to re-introduce this in
the future, but I didn't want to make this tasks system too complicated, and in
order to facilitate a header section in the main view we'd need to have a task
that gets the upstream for the current branch, writes it to the header, then
tells another task to write the branch log to the main view, but without
clearing inbetween. So it would get messy. I'm thinking instead of having a
separate 'header' view atop the main view to render that kind of thing (which
can happen in another PR)
I've also simplified the 'git show' to just call 'git show' and not do anything
fancy when it comes to merge commits.
I considered using this tasks approach whenever we write to a view. The only
thing is that the renderString method currently resets the origin of a view and
I don't want to lose that. So I've left some in there that I consider harmless,
but we should probably be just using tasks now for all rendering, even if it's
just strings we can instantly make.
2020-01-11 05:54:59 +02:00
}
2018-12-08 07:54:54 +02:00
allow fast flicking through any list panel
Up till now our approach to rendering things like file diffs, branch logs, and
commit patches, has been to run a command on the command line, wait for it to
complete, take its output as a string, and then write that string to the main
view (or secondary view e.g. when showing both staged and unstaged changes of a
file).
This has caused various issues. For once, if you are flicking through a list of
files and an untracked file is particularly large, not only will this require
lazygit to load that whole file into memory (or more accurately it's equally
large diff), it also will slow down the UI thread while loading that file, and
if the user continued down the list, the original command might eventually
resolve and replace whatever the diff is for the newly selected file.
Following what we've done in lazydocker, I've added a tasks package for when you
need something done but you want it to cancel as soon as something newer comes
up. Given this typically involves running a command to display to a view, I've
added a viewBufferManagerMap struct to the Gui struct which allows you to define
these tasks on a per-view basis.
viewBufferManagers can run files and directly write the output to their view,
meaning we no longer need to use so much memory.
In the tasks package there is a helper method called NewCmdTask which takes a
command, an initial amount of lines to read, and then runs that command, reads
that number of lines, and allows for a readLines channel to tell it to read more
lines. We read more lines when we scroll or resize the window.
There is an adapter for the tasks package in a file called tasks_adapter which
wraps the functions from the tasks package in gui-specific stuff like clearing
the main view before starting the next task that wants to write to the main
view.
I've removed some small features as part of this work, namely the little headers
that were at the top of the main view for some situations. For example, we no
longer show the upstream of a selected branch. I want to re-introduce this in
the future, but I didn't want to make this tasks system too complicated, and in
order to facilitate a header section in the main view we'd need to have a task
that gets the upstream for the current branch, writes it to the header, then
tells another task to write the branch log to the main view, but without
clearing inbetween. So it would get messy. I'm thinking instead of having a
separate 'header' view atop the main view to render that kind of thing (which
can happen in another PR)
I've also simplified the 'git show' to just call 'git show' and not do anything
fancy when it comes to merge commits.
I considered using this tasks approach whenever we write to a view. The only
thing is that the renderString method currently resets the origin of a view and
I don't want to lose that. So I've left some in there that I consider harmless,
but we should probably be just using tasks now for all rendering, even if it's
just strings we can instantly make.
2020-01-11 05:54:59 +02:00
func ( c * GitCommand ) GetBranchGraphCmdStr ( branchName string ) string {
2020-07-10 10:22:22 +02:00
branchLogCmdTemplate := c . Config . GetUserConfig ( ) . GetString ( "git.branchLogCmd" )
templateValues := map [ string ] string {
"branchName" : branchName ,
}
return utils . ResolvePlaceholderString ( branchLogCmdTemplate , templateValues )
2018-08-12 13:04:47 +02:00
}
2018-10-12 14:06:03 +02:00
// GetRemoteURL returns current repo remote url
func ( c * GitCommand ) GetRemoteURL ( ) string {
url , _ := c . OSCommand . RunCommandWithOutput ( "git config --get remote.origin.url" )
return utils . TrimTrailingNewline ( url )
}
2018-10-17 14:20:15 +02:00
// CheckRemoteBranchExists Returns remote branch
2020-09-29 10:34:01 +02:00
func ( c * GitCommand ) CheckRemoteBranchExists ( branch * models . Branch ) bool {
2019-11-21 12:09:14 +02:00
_ , err := c . OSCommand . RunCommandWithOutput (
2018-10-17 14:20:15 +02:00
"git show-ref --verify -- refs/remotes/origin/%s" ,
branch . Name ,
2019-11-21 12:09:14 +02:00
)
2018-10-17 14:20:15 +02:00
return err == nil
}
2020-08-22 09:26:23 +02:00
// WorktreeFileDiff returns the diff of a file
2020-09-29 10:45:00 +02:00
func ( c * GitCommand ) WorktreeFileDiff ( file * models . File , plain bool , cached bool ) string {
allow fast flicking through any list panel
Up till now our approach to rendering things like file diffs, branch logs, and
commit patches, has been to run a command on the command line, wait for it to
complete, take its output as a string, and then write that string to the main
view (or secondary view e.g. when showing both staged and unstaged changes of a
file).
This has caused various issues. For once, if you are flicking through a list of
files and an untracked file is particularly large, not only will this require
lazygit to load that whole file into memory (or more accurately it's equally
large diff), it also will slow down the UI thread while loading that file, and
if the user continued down the list, the original command might eventually
resolve and replace whatever the diff is for the newly selected file.
Following what we've done in lazydocker, I've added a tasks package for when you
need something done but you want it to cancel as soon as something newer comes
up. Given this typically involves running a command to display to a view, I've
added a viewBufferManagerMap struct to the Gui struct which allows you to define
these tasks on a per-view basis.
viewBufferManagers can run files and directly write the output to their view,
meaning we no longer need to use so much memory.
In the tasks package there is a helper method called NewCmdTask which takes a
command, an initial amount of lines to read, and then runs that command, reads
that number of lines, and allows for a readLines channel to tell it to read more
lines. We read more lines when we scroll or resize the window.
There is an adapter for the tasks package in a file called tasks_adapter which
wraps the functions from the tasks package in gui-specific stuff like clearing
the main view before starting the next task that wants to write to the main
view.
I've removed some small features as part of this work, namely the little headers
that were at the top of the main view for some situations. For example, we no
longer show the upstream of a selected branch. I want to re-introduce this in
the future, but I didn't want to make this tasks system too complicated, and in
order to facilitate a header section in the main view we'd need to have a task
that gets the upstream for the current branch, writes it to the header, then
tells another task to write the branch log to the main view, but without
clearing inbetween. So it would get messy. I'm thinking instead of having a
separate 'header' view atop the main view to render that kind of thing (which
can happen in another PR)
I've also simplified the 'git show' to just call 'git show' and not do anything
fancy when it comes to merge commits.
I considered using this tasks approach whenever we write to a view. The only
thing is that the renderString method currently resets the origin of a view and
I don't want to lose that. So I've left some in there that I consider harmless,
but we should probably be just using tasks now for all rendering, even if it's
just strings we can instantly make.
2020-01-11 05:54:59 +02:00
// for now we assume an error means the file was deleted
2020-08-22 09:26:23 +02:00
s , _ := c . OSCommand . RunCommandWithOutput ( c . WorktreeFileDiffCmdStr ( file , plain , cached ) )
allow fast flicking through any list panel
Up till now our approach to rendering things like file diffs, branch logs, and
commit patches, has been to run a command on the command line, wait for it to
complete, take its output as a string, and then write that string to the main
view (or secondary view e.g. when showing both staged and unstaged changes of a
file).
This has caused various issues. For once, if you are flicking through a list of
files and an untracked file is particularly large, not only will this require
lazygit to load that whole file into memory (or more accurately it's equally
large diff), it also will slow down the UI thread while loading that file, and
if the user continued down the list, the original command might eventually
resolve and replace whatever the diff is for the newly selected file.
Following what we've done in lazydocker, I've added a tasks package for when you
need something done but you want it to cancel as soon as something newer comes
up. Given this typically involves running a command to display to a view, I've
added a viewBufferManagerMap struct to the Gui struct which allows you to define
these tasks on a per-view basis.
viewBufferManagers can run files and directly write the output to their view,
meaning we no longer need to use so much memory.
In the tasks package there is a helper method called NewCmdTask which takes a
command, an initial amount of lines to read, and then runs that command, reads
that number of lines, and allows for a readLines channel to tell it to read more
lines. We read more lines when we scroll or resize the window.
There is an adapter for the tasks package in a file called tasks_adapter which
wraps the functions from the tasks package in gui-specific stuff like clearing
the main view before starting the next task that wants to write to the main
view.
I've removed some small features as part of this work, namely the little headers
that were at the top of the main view for some situations. For example, we no
longer show the upstream of a selected branch. I want to re-introduce this in
the future, but I didn't want to make this tasks system too complicated, and in
order to facilitate a header section in the main view we'd need to have a task
that gets the upstream for the current branch, writes it to the header, then
tells another task to write the branch log to the main view, but without
clearing inbetween. So it would get messy. I'm thinking instead of having a
separate 'header' view atop the main view to render that kind of thing (which
can happen in another PR)
I've also simplified the 'git show' to just call 'git show' and not do anything
fancy when it comes to merge commits.
I considered using this tasks approach whenever we write to a view. The only
thing is that the renderString method currently resets the origin of a view and
I don't want to lose that. So I've left some in there that I consider harmless,
but we should probably be just using tasks now for all rendering, even if it's
just strings we can instantly make.
2020-01-11 05:54:59 +02:00
return s
}
2020-09-29 10:45:00 +02:00
func ( c * GitCommand ) WorktreeFileDiffCmdStr ( file * models . File , plain bool , cached bool ) string {
2018-08-12 13:04:47 +02:00
cachedArg := ""
2018-09-18 21:09:51 +02:00
trackedArg := "--"
2020-03-01 03:30:48 +02:00
colorArg := c . colorArg ( )
2019-02-20 10:47:01 +02:00
split := strings . Split ( file . Name , " -> " ) // in case of a renamed file we get the new filename
fileName := c . OSCommand . Quote ( split [ len ( split ) - 1 ] )
2019-10-30 11:23:25 +02:00
if cached {
2018-08-14 10:48:08 +02:00
cachedArg = "--cached"
2018-08-12 13:04:47 +02:00
}
2020-02-03 21:05:01 +02:00
if ! file . Tracked && ! file . HasStagedChanges && ! cached {
2018-08-14 10:48:08 +02:00
trackedArg = "--no-index /dev/null"
2018-08-12 13:04:47 +02:00
}
2018-12-02 10:57:01 +02:00
if plain {
2020-03-01 03:30:48 +02:00
colorArg = "never"
2018-12-02 10:57:01 +02:00
}
2020-09-28 00:21:53 +02:00
return fmt . Sprintf ( "git diff --submodule --no-ext-diff --color=%s %s %s %s" , colorArg , cachedArg , trackedArg , fileName )
2018-08-12 13:04:47 +02:00
}
2018-12-02 10:57:01 +02:00
2019-11-05 09:44:46 +02:00
func ( c * GitCommand ) ApplyPatch ( patch string , flags ... string ) error {
2020-01-05 21:57:18 +02:00
filepath := filepath . Join ( c . Config . GetUserConfigDir ( ) , utils . GetCurrentRepoName ( ) , time . Now ( ) . Format ( "Jan _2 15.04.05.000000000" ) + ".patch" )
2020-09-26 02:23:10 +02:00
c . Log . Infof ( "saving temporary patch to %s" , filepath )
2019-11-05 03:42:07 +02:00
if err := c . OSCommand . CreateFileWithContent ( filepath , patch ) ; err != nil {
2019-11-04 10:47:25 +02:00
return err
2018-12-02 10:57:01 +02:00
}
2019-11-05 09:44:46 +02:00
flagStr := ""
for _ , flag := range flags {
flagStr += " --" + flag
2019-10-30 11:23:25 +02:00
}
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git apply %s %s" , flagStr , c . OSCommand . Quote ( filepath ) )
2018-12-02 10:57:01 +02:00
}
2018-12-07 09:52:31 +02:00
2020-08-11 13:52:43 +02:00
func ( c * GitCommand ) FastForward ( branchName string , remoteName string , remoteBranchName string , promptUserForCredential func ( string ) string ) error {
command := fmt . Sprintf ( "git fetch %s %s:%s" , remoteName , remoteBranchName , branchName )
return c . OSCommand . DetectUnamePass ( command , promptUserForCredential )
2018-12-07 09:52:31 +02:00
}
2019-02-16 12:01:17 +02:00
2019-03-03 03:44:10 +02:00
func ( c * GitCommand ) RunSkipEditorCommand ( command string ) error {
cmd := c . OSCommand . ExecutableFromString ( command )
2020-02-01 22:57:30 +02:00
lazyGitPath := c . OSCommand . GetLazygitPath ( )
2019-03-03 03:44:10 +02:00
cmd . Env = append (
2019-06-06 12:33:25 +02:00
cmd . Env ,
2019-03-03 03:44:10 +02:00
"LAZYGIT_CLIENT_COMMAND=EXIT_IMMEDIATELY" ,
2020-03-27 00:16:41 +02:00
"GIT_EDITOR=" + lazyGitPath ,
2020-02-01 22:57:30 +02:00
"EDITOR=" + lazyGitPath ,
"VISUAL=" + lazyGitPath ,
2019-03-03 03:44:10 +02:00
)
return c . OSCommand . RunExecutable ( cmd )
}
2019-02-19 14:36:29 +02:00
// GenericMerge takes a commandType of "merge" or "rebase" and a command of "abort", "skip" or "continue"
2019-02-16 12:01:17 +02:00
// By default we skip the editor in the case where a commit will be made
func ( c * GitCommand ) GenericMerge ( commandType string , command string ) error {
2019-11-04 10:47:25 +02:00
err := c . RunSkipEditorCommand (
2019-03-03 03:44:10 +02:00
fmt . Sprintf (
"git %s --%s" ,
commandType ,
command ,
) ,
)
2019-11-04 10:47:25 +02:00
if err != nil {
2020-03-28 03:52:45 +02:00
if ! strings . Contains ( err . Error ( ) , "no rebase in progress" ) {
return err
}
c . Log . Warn ( err )
2019-11-04 10:47:25 +02:00
}
// sometimes we need to do a sequence of things in a rebase but the user needs to
// fix merge conflicts along the way. When this happens we queue up the next step
// so that after the next successful rebase continue we can continue from where we left off
if commandType == "rebase" && command == "continue" && c . onSuccessfulContinue != nil {
f := c . onSuccessfulContinue
c . onSuccessfulContinue = nil
return f ( )
}
if command == "abort" {
c . onSuccessfulContinue = nil
}
return nil
2019-02-16 12:01:17 +02:00
}
2019-02-18 12:29:43 +02:00
2020-09-29 10:36:54 +02:00
func ( c * GitCommand ) RewordCommit ( commits [ ] * models . Commit , index int ) ( * exec . Cmd , error ) {
2019-04-07 01:10:58 +02:00
todo , sha , err := c . GenerateGenericRebaseTodo ( commits , index , "reword" )
2019-02-18 12:29:43 +02:00
if err != nil {
2019-02-18 14:27:54 +02:00
return nil , err
2019-02-18 12:29:43 +02:00
}
2019-04-07 01:10:58 +02:00
return c . PrepareInteractiveRebaseCommand ( sha , todo , false )
2019-02-18 14:27:54 +02:00
}
2020-09-29 10:36:54 +02:00
func ( c * GitCommand ) MoveCommitDown ( commits [ ] * models . Commit , index int ) error {
2019-02-18 14:27:54 +02:00
// we must ensure that we have at least two commits after the selected one
if len ( commits ) <= index + 2 {
// assuming they aren't picking the bottom commit
2019-02-20 11:51:24 +02:00
return errors . New ( c . Tr . SLocalize ( "NoRoom" ) )
2019-02-18 12:29:43 +02:00
}
todo := ""
2019-02-18 14:27:54 +02:00
orderedCommits := append ( commits [ 0 : index ] , commits [ index + 1 ] , commits [ index ] )
for _ , commit := range orderedCommits {
2019-02-19 14:36:29 +02:00
todo = "pick " + commit . Sha + " " + commit . Name + "\n" + todo
2019-02-18 14:27:54 +02:00
}
2019-02-19 00:03:29 +02:00
cmd , err := c . PrepareInteractiveRebaseCommand ( commits [ index + 2 ] . Sha , todo , true )
2019-02-18 14:27:54 +02:00
if err != nil {
return err
}
return c . OSCommand . RunPreparedCommand ( cmd )
}
2020-09-29 10:36:54 +02:00
func ( c * GitCommand ) InteractiveRebase ( commits [ ] * models . Commit , index int , action string ) error {
2019-04-07 01:10:58 +02:00
todo , sha , err := c . GenerateGenericRebaseTodo ( commits , index , action )
2019-02-18 14:27:54 +02:00
if err != nil {
return err
}
2019-04-07 01:10:58 +02:00
cmd , err := c . PrepareInteractiveRebaseCommand ( sha , todo , true )
2019-02-18 14:27:54 +02:00
if err != nil {
return err
}
return c . OSCommand . RunPreparedCommand ( cmd )
}
2019-03-03 03:44:10 +02:00
// PrepareInteractiveRebaseCommand returns the cmd for an interactive rebase
// we tell git to run lazygit to edit the todo list, and we pass the client
// lazygit a todo string to write to the todo file
2019-02-19 14:36:29 +02:00
func ( c * GitCommand ) PrepareInteractiveRebaseCommand ( baseSha string , todo string , overrideEditor bool ) ( * exec . Cmd , error ) {
2019-03-03 03:44:10 +02:00
ex := c . OSCommand . GetLazygitPath ( )
2019-02-18 12:29:43 +02:00
debug := "FALSE"
2019-07-19 03:46:07 +02:00
if c . OSCommand . Config . GetDebug ( ) {
2019-02-18 12:29:43 +02:00
debug = "TRUE"
}
2020-08-27 09:00:43 +02:00
cmdStr := fmt . Sprintf ( "git rebase --interactive --autostash --keep-empty %s" , baseSha )
2020-09-26 02:45:13 +02:00
c . Log . WithField ( "command" , cmdStr ) . Info ( "RunCommand" )
2020-08-27 09:00:43 +02:00
splitCmd := str . ToArgv ( cmdStr )
2019-02-18 12:29:43 +02:00
2020-09-29 11:10:57 +02:00
cmd := c . OSCommand . Command ( splitCmd [ 0 ] , splitCmd [ 1 : ] ... )
2019-02-18 12:29:43 +02:00
2019-02-24 00:42:24 +02:00
gitSequenceEditor := ex
if todo == "" {
gitSequenceEditor = "true"
}
2019-02-18 12:29:43 +02:00
cmd . Env = os . Environ ( )
cmd . Env = append (
cmd . Env ,
2019-03-03 03:44:10 +02:00
"LAZYGIT_CLIENT_COMMAND=INTERACTIVE_REBASE" ,
2019-02-18 12:29:43 +02:00
"LAZYGIT_REBASE_TODO=" + todo ,
"DEBUG=" + debug ,
"LANG=en_US.UTF-8" , // Force using EN as language
"LC_ALL=en_US.UTF-8" , // Force using EN as language
2019-02-24 00:42:24 +02:00
"GIT_SEQUENCE_EDITOR=" + gitSequenceEditor ,
2019-02-18 12:29:43 +02:00
)
2019-02-19 14:36:29 +02:00
if overrideEditor {
2020-03-27 00:16:41 +02:00
cmd . Env = append ( cmd . Env , "GIT_EDITOR=" + ex )
2019-02-19 14:36:29 +02:00
}
2019-02-18 14:27:54 +02:00
return cmd , nil
}
func ( c * GitCommand ) HardReset ( baseSha string ) error {
return c . OSCommand . RunCommand ( "git reset --hard " + baseSha )
}
2019-02-19 14:36:29 +02:00
func ( c * GitCommand ) SoftReset ( baseSha string ) error {
return c . OSCommand . RunCommand ( "git reset --soft " + baseSha )
}
2020-09-29 10:36:54 +02:00
func ( c * GitCommand ) GenerateGenericRebaseTodo ( commits [ ] * models . Commit , actionIndex int , action string ) ( string , string , error ) {
2019-04-07 01:10:58 +02:00
baseIndex := actionIndex + 1
if len ( commits ) <= baseIndex {
return "" , "" , errors . New ( c . Tr . SLocalize ( "CannotRebaseOntoFirstCommit" ) )
}
if action == "squash" || action == "fixup" {
baseIndex ++
if len ( commits ) <= baseIndex {
return "" , "" , errors . New ( c . Tr . SLocalize ( "CannotSquashOntoSecondCommit" ) )
}
2019-02-18 12:29:43 +02:00
}
2019-02-18 14:27:54 +02:00
todo := ""
2019-04-07 01:10:58 +02:00
for i , commit := range commits [ 0 : baseIndex ] {
2020-08-27 09:00:43 +02:00
var commitAction string
2019-04-07 01:10:58 +02:00
if i == actionIndex {
2020-08-27 09:00:43 +02:00
commitAction = action
} else if commit . IsMerge {
// your typical interactive rebase will actually drop merge commits by default. Damn git CLI, you scary!
// doing this means we don't need to worry about rebasing over merges which always causes problems.
// you typically shouldn't be doing rebases that pass over merge commits anyway.
commitAction = "drop"
} else {
commitAction = "pick"
2019-02-18 12:29:43 +02:00
}
2020-08-27 09:00:43 +02:00
todo = commitAction + " " + commit . Sha + " " + commit . Name + "\n" + todo
2019-02-18 12:29:43 +02:00
}
2019-04-07 01:10:58 +02:00
return todo , commits [ baseIndex ] . Sha , nil
2019-02-18 12:29:43 +02:00
}
2019-02-19 14:36:29 +02:00
// AmendTo amends the given commit with whatever files are staged
func ( c * GitCommand ) AmendTo ( sha string ) error {
2019-04-07 03:35:34 +02:00
if err := c . CreateFixupCommit ( sha ) ; err != nil {
2019-02-19 14:36:29 +02:00
return err
}
2019-04-07 03:35:34 +02:00
return c . SquashAllAboveFixupCommits ( sha )
2019-02-19 14:36:29 +02:00
}
2019-02-20 11:51:24 +02:00
// EditRebaseTodo sets the action at a given index in the git-rebase-todo file
2019-02-19 14:36:29 +02:00
func ( c * GitCommand ) EditRebaseTodo ( index int , action string ) error {
2020-09-27 08:17:26 +02:00
fileName := filepath . Join ( c . DotGitDir , "rebase-merge/git-rebase-todo" )
2019-02-19 14:36:29 +02:00
bytes , err := ioutil . ReadFile ( fileName )
if err != nil {
return err
}
content := strings . Split ( string ( bytes ) , "\n" )
2019-03-02 11:57:18 +02:00
commitCount := c . getTodoCommitCount ( content )
2019-02-24 00:42:24 +02:00
// we have the most recent commit at the bottom whereas the todo file has
// it at the bottom, so we need to subtract our index from the commit count
contentIndex := commitCount - 1 - index
2019-02-19 14:36:29 +02:00
splitLine := strings . Split ( content [ contentIndex ] , " " )
content [ contentIndex ] = action + " " + strings . Join ( splitLine [ 1 : ] , " " )
result := strings . Join ( content , "\n" )
return ioutil . WriteFile ( fileName , [ ] byte ( result ) , 0644 )
}
2019-03-02 11:57:18 +02:00
func ( c * GitCommand ) getTodoCommitCount ( content [ ] string ) int {
// count lines that are not blank and are not comments
commitCount := 0
for _ , line := range content {
if line != "" && ! strings . HasPrefix ( line , "#" ) {
commitCount ++
}
}
return commitCount
}
2019-02-20 11:51:24 +02:00
// MoveTodoDown moves a rebase todo item down by one position
func ( c * GitCommand ) MoveTodoDown ( index int ) error {
2020-09-27 08:17:26 +02:00
fileName := filepath . Join ( c . DotGitDir , "rebase-merge/git-rebase-todo" )
2019-02-20 11:51:24 +02:00
bytes , err := ioutil . ReadFile ( fileName )
if err != nil {
return err
}
content := strings . Split ( string ( bytes ) , "\n" )
2019-03-02 11:57:18 +02:00
commitCount := c . getTodoCommitCount ( content )
contentIndex := commitCount - 1 - index
2019-02-20 11:51:24 +02:00
rearrangedContent := append ( content [ 0 : contentIndex - 1 ] , content [ contentIndex ] , content [ contentIndex - 1 ] )
rearrangedContent = append ( rearrangedContent , content [ contentIndex + 1 : ] ... )
result := strings . Join ( rearrangedContent , "\n" )
return ioutil . WriteFile ( fileName , [ ] byte ( result ) , 0644 )
}
2019-02-19 14:36:29 +02:00
// Revert reverts the selected commit by sha
func ( c * GitCommand ) Revert ( sha string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git revert %s" , sha )
2019-02-19 14:36:29 +02:00
}
2019-02-24 04:51:52 +02:00
2019-02-24 08:34:19 +02:00
// CherryPickCommits begins an interactive rebase with the given shas being cherry picked onto HEAD
2020-09-29 10:36:54 +02:00
func ( c * GitCommand ) CherryPickCommits ( commits [ ] * models . Commit ) error {
2019-02-24 04:51:52 +02:00
todo := ""
2019-02-24 08:34:19 +02:00
for _ , commit := range commits {
todo = "pick " + commit . Sha + " " + commit . Name + "\n" + todo
2019-02-24 04:51:52 +02:00
}
cmd , err := c . PrepareInteractiveRebaseCommand ( "HEAD" , todo , false )
if err != nil {
return err
}
return c . OSCommand . RunPreparedCommand ( cmd )
}
2019-03-09 16:42:10 +02:00
2020-08-22 10:29:09 +02:00
// ShowFileDiff get the diff of specified from and to. Typically this will be used for a single commit so it'll be 123abc^..123abc
// but when we're in diff mode it could be any 'from' to any 'to'. The reverse flag is also here thanks to diff mode.
func ( c * GitCommand ) ShowFileDiff ( from string , to string , reverse bool , fileName string , plain bool ) ( string , error ) {
cmdStr := c . ShowFileDiffCmdStr ( from , to , reverse , fileName , plain )
allow fast flicking through any list panel
Up till now our approach to rendering things like file diffs, branch logs, and
commit patches, has been to run a command on the command line, wait for it to
complete, take its output as a string, and then write that string to the main
view (or secondary view e.g. when showing both staged and unstaged changes of a
file).
This has caused various issues. For once, if you are flicking through a list of
files and an untracked file is particularly large, not only will this require
lazygit to load that whole file into memory (or more accurately it's equally
large diff), it also will slow down the UI thread while loading that file, and
if the user continued down the list, the original command might eventually
resolve and replace whatever the diff is for the newly selected file.
Following what we've done in lazydocker, I've added a tasks package for when you
need something done but you want it to cancel as soon as something newer comes
up. Given this typically involves running a command to display to a view, I've
added a viewBufferManagerMap struct to the Gui struct which allows you to define
these tasks on a per-view basis.
viewBufferManagers can run files and directly write the output to their view,
meaning we no longer need to use so much memory.
In the tasks package there is a helper method called NewCmdTask which takes a
command, an initial amount of lines to read, and then runs that command, reads
that number of lines, and allows for a readLines channel to tell it to read more
lines. We read more lines when we scroll or resize the window.
There is an adapter for the tasks package in a file called tasks_adapter which
wraps the functions from the tasks package in gui-specific stuff like clearing
the main view before starting the next task that wants to write to the main
view.
I've removed some small features as part of this work, namely the little headers
that were at the top of the main view for some situations. For example, we no
longer show the upstream of a selected branch. I want to re-introduce this in
the future, but I didn't want to make this tasks system too complicated, and in
order to facilitate a header section in the main view we'd need to have a task
that gets the upstream for the current branch, writes it to the header, then
tells another task to write the branch log to the main view, but without
clearing inbetween. So it would get messy. I'm thinking instead of having a
separate 'header' view atop the main view to render that kind of thing (which
can happen in another PR)
I've also simplified the 'git show' to just call 'git show' and not do anything
fancy when it comes to merge commits.
I considered using this tasks approach whenever we write to a view. The only
thing is that the renderString method currently resets the origin of a view and
I don't want to lose that. So I've left some in there that I consider harmless,
but we should probably be just using tasks now for all rendering, even if it's
just strings we can instantly make.
2020-01-11 05:54:59 +02:00
return c . OSCommand . RunCommandWithOutput ( cmdStr )
}
2020-08-22 10:29:09 +02:00
func ( c * GitCommand ) ShowFileDiffCmdStr ( from string , to string , reverse bool , fileName string , plain bool ) string {
2020-03-01 03:30:48 +02:00
colorArg := c . colorArg ( )
2019-11-04 10:47:25 +02:00
if plain {
2020-03-01 03:30:48 +02:00
colorArg = "never"
2019-11-04 10:47:25 +02:00
}
allow fast flicking through any list panel
Up till now our approach to rendering things like file diffs, branch logs, and
commit patches, has been to run a command on the command line, wait for it to
complete, take its output as a string, and then write that string to the main
view (or secondary view e.g. when showing both staged and unstaged changes of a
file).
This has caused various issues. For once, if you are flicking through a list of
files and an untracked file is particularly large, not only will this require
lazygit to load that whole file into memory (or more accurately it's equally
large diff), it also will slow down the UI thread while loading that file, and
if the user continued down the list, the original command might eventually
resolve and replace whatever the diff is for the newly selected file.
Following what we've done in lazydocker, I've added a tasks package for when you
need something done but you want it to cancel as soon as something newer comes
up. Given this typically involves running a command to display to a view, I've
added a viewBufferManagerMap struct to the Gui struct which allows you to define
these tasks on a per-view basis.
viewBufferManagers can run files and directly write the output to their view,
meaning we no longer need to use so much memory.
In the tasks package there is a helper method called NewCmdTask which takes a
command, an initial amount of lines to read, and then runs that command, reads
that number of lines, and allows for a readLines channel to tell it to read more
lines. We read more lines when we scroll or resize the window.
There is an adapter for the tasks package in a file called tasks_adapter which
wraps the functions from the tasks package in gui-specific stuff like clearing
the main view before starting the next task that wants to write to the main
view.
I've removed some small features as part of this work, namely the little headers
that were at the top of the main view for some situations. For example, we no
longer show the upstream of a selected branch. I want to re-introduce this in
the future, but I didn't want to make this tasks system too complicated, and in
order to facilitate a header section in the main view we'd need to have a task
that gets the upstream for the current branch, writes it to the header, then
tells another task to write the branch log to the main view, but without
clearing inbetween. So it would get messy. I'm thinking instead of having a
separate 'header' view atop the main view to render that kind of thing (which
can happen in another PR)
I've also simplified the 'git show' to just call 'git show' and not do anything
fancy when it comes to merge commits.
I considered using this tasks approach whenever we write to a view. The only
thing is that the renderString method currently resets the origin of a view and
I don't want to lose that. So I've left some in there that I consider harmless,
but we should probably be just using tasks now for all rendering, even if it's
just strings we can instantly make.
2020-01-11 05:54:59 +02:00
2020-08-22 10:29:09 +02:00
reverseFlag := ""
if reverse {
reverseFlag = " -R "
}
2020-09-28 00:21:53 +02:00
return fmt . Sprintf ( "git diff --submodule --no-ext-diff --no-renames --color=%s %s %s %s -- %s" , colorArg , from , to , reverseFlag , fileName )
2019-03-09 16:42:10 +02:00
}
2019-03-11 00:53:46 +02:00
// CheckoutFile checks out the file for the given commit
func ( c * GitCommand ) CheckoutFile ( commitSha , fileName string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git checkout %s %s" , commitSha , fileName )
2019-03-11 00:53:46 +02:00
}
2019-03-11 04:04:08 +02:00
// DiscardOldFileChanges discards changes to a file from an old commit
2020-09-29 10:36:54 +02:00
func ( c * GitCommand ) DiscardOldFileChanges ( commits [ ] * models . Commit , commitIndex int , fileName string ) error {
2019-11-04 10:47:25 +02:00
if err := c . BeginInteractiveRebaseForCommit ( commits , commitIndex ) ; err != nil {
2019-03-11 04:04:08 +02:00
return err
}
// check if file exists in previous commit (this command returns an error if the file doesn't exist)
2019-11-21 12:09:14 +02:00
if err := c . OSCommand . RunCommand ( "git cat-file -e HEAD^:%s" , fileName ) ; err != nil {
2019-03-18 11:44:33 +02:00
if err := c . OSCommand . Remove ( fileName ) ; err != nil {
2019-03-11 04:04:08 +02:00
return err
}
if err := c . StageFile ( fileName ) ; err != nil {
return err
}
2019-07-19 04:00:02 +02:00
} else if err := c . CheckoutFile ( "HEAD^" , fileName ) ; err != nil {
return err
2019-03-11 04:04:08 +02:00
}
// amend the commit
2019-11-04 10:47:25 +02:00
cmd , err := c . AmendHead ( )
2019-03-11 04:04:08 +02:00
if cmd != nil {
2019-03-12 10:20:19 +02:00
return errors . New ( "received unexpected pointer to cmd" )
2019-03-11 04:04:08 +02:00
}
if err != nil {
return err
}
// continue
return c . GenericMerge ( "rebase" , "continue" )
}
2019-03-18 12:19:07 +02:00
// DiscardAnyUnstagedFileChanges discards any unstages file changes via `git checkout -- .`
func ( c * GitCommand ) DiscardAnyUnstagedFileChanges ( ) error {
return c . OSCommand . RunCommand ( "git checkout -- ." )
}
2020-02-04 13:50:13 +02:00
// RemoveTrackedFiles will delete the given file(s) even if they are currently tracked
func ( c * GitCommand ) RemoveTrackedFiles ( name string ) error {
return c . OSCommand . RunCommand ( "git rm -r --cached %s" , name )
}
2019-03-18 12:19:07 +02:00
// RemoveUntrackedFiles runs `git clean -fd`
func ( c * GitCommand ) RemoveUntrackedFiles ( ) error {
return c . OSCommand . RunCommand ( "git clean -fd" )
}
2020-01-07 11:12:36 +02:00
// ResetHardHead runs `git reset --hard`
func ( c * GitCommand ) ResetHard ( ref string ) error {
return c . OSCommand . RunCommand ( "git reset --hard " + ref )
2019-03-18 12:19:07 +02:00
}
2019-03-18 12:40:32 +02:00
2020-01-07 11:12:36 +02:00
// ResetSoft runs `git reset --soft HEAD`
func ( c * GitCommand ) ResetSoft ( ref string ) error {
return c . OSCommand . RunCommand ( "git reset --soft " + ref )
2019-03-18 12:40:32 +02:00
}
2019-03-23 15:46:08 +02:00
2019-04-07 03:35:34 +02:00
// CreateFixupCommit creates a commit that fixes up a previous commit
func ( c * GitCommand ) CreateFixupCommit ( sha string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git commit --fixup=%s" , sha )
2019-04-07 03:35:34 +02:00
}
// SquashAllAboveFixupCommits squashes all fixup! commits above the given one
func ( c * GitCommand ) SquashAllAboveFixupCommits ( sha string ) error {
return c . RunSkipEditorCommand (
fmt . Sprintf (
"git rebase --interactive --autostash --autosquash %s^" ,
sha ,
) ,
)
}
2019-05-30 14:45:56 +02:00
// StashSaveStagedChanges stashes only the currently staged changes. This takes a few steps
// shoutouts to Joe on https://stackoverflow.com/questions/14759748/stashing-only-staged-changes-in-git-is-it-possible
func ( c * GitCommand ) StashSaveStagedChanges ( message string ) error {
if err := c . OSCommand . RunCommand ( "git stash --keep-index" ) ; err != nil {
return err
}
if err := c . StashSave ( message ) ; err != nil {
return err
}
if err := c . OSCommand . RunCommand ( "git stash apply stash@{1}" ) ; err != nil {
return err
}
if err := c . OSCommand . PipeCommands ( "git stash show -p" , "git apply -R" ) ; err != nil {
return err
}
if err := c . OSCommand . RunCommand ( "git stash drop stash@{1}" ) ; err != nil {
return err
}
// if you had staged an untracked file, that will now appear as 'AD' in git status
// meaning it's deleted in your working tree but added in your index. Given that it's
// now safely stashed, we need to remove it.
2020-08-07 09:52:17 +02:00
files := c . GetStatusFiles ( GetStatusFileOptions { } )
2019-05-30 14:45:56 +02:00
for _ , file := range files {
if file . ShortStatus == "AD" {
if err := c . UnStageFile ( file . Name , false ) ; err != nil {
return err
}
}
}
return nil
}
2019-11-04 10:47:25 +02:00
// BeginInteractiveRebaseForCommit starts an interactive rebase to edit the current
// commit and pick all others. After this you'll want to call `c.GenericMerge("rebase", "continue")`
2020-09-29 10:36:54 +02:00
func ( c * GitCommand ) BeginInteractiveRebaseForCommit ( commits [ ] * models . Commit , commitIndex int ) error {
2019-11-04 10:47:25 +02:00
if len ( commits ) - 1 < commitIndex {
return errors . New ( "index outside of range of commits" )
}
// we can make this GPG thing possible it just means we need to do this in two parts:
// one where we handle the possibility of a credential request, and the other
// where we continue the rebase
if c . usingGpg ( ) {
return errors . New ( c . Tr . SLocalize ( "DisabledForGPG" ) )
}
todo , sha , err := c . GenerateGenericRebaseTodo ( commits , commitIndex , "edit" )
if err != nil {
return err
}
cmd , err := c . PrepareInteractiveRebaseCommand ( sha , todo , true )
if err != nil {
return err
}
if err := c . OSCommand . RunPreparedCommand ( cmd ) ; err != nil {
return err
}
return nil
}
2019-11-13 12:16:24 +02:00
func ( c * GitCommand ) SetUpstreamBranch ( upstream string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git branch -u %s" , upstream )
2019-11-13 12:16:24 +02:00
}
2019-11-17 03:02:39 +02:00
func ( c * GitCommand ) AddRemote ( name string , url string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git remote add %s %s" , name , url )
2019-11-17 03:02:39 +02:00
}
func ( c * GitCommand ) RemoveRemote ( name string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git remote remove %s" , name )
2019-11-17 03:02:39 +02:00
}
2019-11-17 04:21:38 +02:00
func ( c * GitCommand ) IsHeadDetached ( ) bool {
err := c . OSCommand . RunCommand ( "git symbolic-ref -q HEAD" )
return err != nil
}
2019-11-17 04:47:47 +02:00
func ( c * GitCommand ) DeleteRemoteBranch ( remoteName string , branchName string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git push %s --delete %s" , remoteName , branchName )
2019-11-17 04:47:47 +02:00
}
2019-11-17 05:50:12 +02:00
func ( c * GitCommand ) SetBranchUpstream ( remoteName string , remoteBranchName string , branchName string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git branch --set-upstream-to=%s/%s %s" , remoteName , remoteBranchName , branchName )
2019-11-17 05:50:12 +02:00
}
2019-11-17 09:15:32 +02:00
func ( c * GitCommand ) RenameRemote ( oldRemoteName string , newRemoteName string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git remote rename %s %s" , oldRemoteName , newRemoteName )
2019-11-17 09:15:32 +02:00
}
func ( c * GitCommand ) UpdateRemoteUrl ( remoteName string , updatedUrl string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git remote set-url %s %s" , remoteName , updatedUrl )
2019-11-17 09:15:32 +02:00
}
2019-11-18 00:38:36 +02:00
func ( c * GitCommand ) CreateLightweightTag ( tagName string , commitSha string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git tag %s %s" , tagName , commitSha )
2019-11-18 00:38:36 +02:00
}
func ( c * GitCommand ) DeleteTag ( tagName string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git tag -d %s" , tagName )
2019-11-18 00:38:36 +02:00
}
func ( c * GitCommand ) PushTag ( remoteName string , tagName string ) error {
2019-11-21 12:09:14 +02:00
return c . OSCommand . RunCommand ( "git push %s %s" , remoteName , tagName )
2019-11-18 00:38:36 +02:00
}
2019-12-07 07:20:22 +02:00
func ( c * GitCommand ) FetchRemote ( remoteName string ) error {
return c . OSCommand . RunCommand ( "git fetch %s" , remoteName )
}
2020-01-09 12:34:17 +02:00
2020-03-01 12:00:44 +02:00
func ( c * GitCommand ) ConfiguredPager ( ) string {
if os . Getenv ( "GIT_PAGER" ) != "" {
return os . Getenv ( "GIT_PAGER" )
2020-03-01 03:30:48 +02:00
}
2020-03-01 12:00:44 +02:00
if os . Getenv ( "PAGER" ) != "" {
return os . Getenv ( "PAGER" )
}
output , err := c . OSCommand . RunCommandWithOutput ( "git config --get-all core.pager" )
if err != nil {
return ""
}
trimmedOutput := strings . TrimSpace ( output )
return strings . Split ( trimmedOutput , "\n" ) [ 0 ]
2020-03-01 03:30:48 +02:00
}
2020-03-01 12:00:44 +02:00
func ( c * GitCommand ) GetPager ( width int ) string {
useConfig := c . Config . GetUserConfig ( ) . GetBool ( "git.paging.useConfig" )
if useConfig {
pager := c . ConfiguredPager ( )
return strings . Split ( pager , "| less" ) [ 0 ]
}
templateValues := map [ string ] string {
"columnWidth" : strconv . Itoa ( width / 2 - 6 ) ,
2020-03-01 03:30:48 +02:00
}
2020-03-01 12:00:44 +02:00
pagerTemplate := c . Config . GetUserConfig ( ) . GetString ( "git.paging.pager" )
return utils . ResolvePlaceholderString ( pagerTemplate , templateValues )
}
func ( c * GitCommand ) colorArg ( ) string {
return c . Config . GetUserConfig ( ) . GetString ( "git.paging.colorArg" )
2020-03-01 03:30:48 +02:00
}
2020-03-17 12:22:07 +02:00
func ( c * GitCommand ) RenameBranch ( oldName string , newName string ) error {
return c . OSCommand . RunCommand ( "git branch --move %s %s" , oldName , newName )
}
2020-03-28 03:08:13 +02:00
func ( c * GitCommand ) WorkingTreeState ( ) string {
rebaseMode , _ := c . RebaseMode ( )
if rebaseMode != "" {
return "rebasing"
}
merging , _ := c . IsInMergeState ( )
if merging {
return "merging"
}
return "normal"
}
2020-09-27 08:02:20 +02:00
func ( c * GitCommand ) IsBareRepo ( ) bool {
// note: could use `git rev-parse --is-bare-repository` if we wanna drop go-git
_ , err := c . Repo . Worktree ( )
return err == gogit . ErrIsBareRepository
}