etc./StackOverFlow

git에서 이름으로 숨김의 이름을 지정하고 검색하는 방법은 무엇입니까?

청렴결백한 만능 재주꾼 2021. 12. 31. 03:33
반응형

질문자 :Suan


git stash save stashname 을 수행하여 숨김에 이름을 지정할 수 있다는 인상을 받았습니다. git stash apply stashname 을 수행하여 적용할 수 있습니다. 그러나 이 경우 발생하는 모든 stashname 이 stash 설명으로 사용되는 것입니다.

실제로 stash의 이름을 지정할 수 있는 방법은 없나요? 그렇지 않다면 동등한 기능을 달성하기 위해 무엇을 권장하시겠습니까? 본질적으로 나는 주기적으로 적용하고 싶은 작은 숨김이 있지만 git stash list 에서 실제 숨김 번호가 무엇인지 항상 검색하고 싶지는 않습니다.



다음과 같이 하십시오.

 git stash push -m "my_stash"

여기서 "my_stash" 는 숨김 이름입니다.

알아야 할 몇 가지 더 유용한 정보: 모든 은닉은 스택에 저장됩니다. 유형:

 git stash list

이렇게 하면 모든 숨김 목록이 나열됩니다.

stash를 적용하고 stash 스택에서 제거하려면 다음을 입력하십시오.

 git stash pop stash@{n}

stash를 적용하고 stash 스택에 유지하려면 다음을 입력하십시오.

 git stash apply stash@{n}

여기서 n 은 숨긴 변경 사항의 인덱스입니다.

stash 이름을 사용하여 stash를 적용하고 스택에 보관할 수 있습니다.

 git stash apply my_stash_name

Sri Murthy Upadhyayula

git stash save 는 2.15.x/2.16부터 더 이상 사용되지 않으며 git stash push -m "message"

다음과 같이 사용할 수 있습니다.

git stash push -m "message"

여기서 "message"는 해당 보관함에 대한 메모입니다.

숨김을 검색하려면 git stash list 사용할 수 있습니다. 예를 들어 다음과 같은 목록이 출력됩니다.

 stash@{0}: On develop: perf-spike stash@{1}: On develop: node v10

stash@{index} 제공 apply 하기만 하면 됩니다.

 git stash apply stash@{1}

참조는 숨겨 놓은 사람이 페이지를 이눔


EssaidiM

현재 작업 복사본 변경 사항의 일부 또는 전체를 저장하고 나중에 원하는 대로 다시 적용하는 간단한 방법을 찾고 있다면 패치 파일을 고려하십시오.

 # save your working copy changes git diff > some.patch # re-apply it later git apply some.patch

때때로 나는 이것을 위해 은닉을 사용해야하는지 궁금합니다. 그러면 위의 광기와 같은 것을 볼 수 있으며 내가하고있는 일에 만족합니다. :)


Pat Niemeyer

충분히 중요하다고 생각되면 숨김을 분기로 전환할 수 있습니다.

 git stash branch <branchname> [<stash>]

매뉴얼 페이지에서 :

이 만들고라는 새 브랜치를 체크 아웃 <branchname> 커밋에서 시작되는 <stash> 처음에 만들에 기록 변경 적용 <stash> 새로운 작업 트리와 인덱스는 다음 떨어질 <stash> 이 경우 성공적으로 완료됩니다. <stash> 가 제공되지 않으면 최신 항목을 적용합니다.

git stash save 를 실행한 분기가 충돌로 인해 git stash apply가 실패할 정도로 변경되었을 때 유용합니다. git stash가 실행될 당시 HEAD였던 커밋 위에 stash가 적용되기 때문에 충돌 없이 원래 stashed 상태로 복원됩니다.

나중에 이 새 분기를 숨겼을 때 있던 위치의 후손인 다른 위치로 리베이스할 수 있습니다.


Adam Dymitruk

은닉은 당신이 원하는 것처럼 영구적인 것을 의미하지 않습니다. 커밋에 태그를 사용하는 것이 더 나을 것입니다. 숨기고 싶은 물건을 만드세요. 커밋하십시오. 해당 커밋에 대한 태그를 만듭니다. 그런 다음 분기를 HEAD^ 롤백하십시오. 이제 해당 숨김을 다시 적용하려면 git cherry-pick -n tagname ( -n--no-commit )을 사용할 수 있습니다.


Lily Ballard

git stash push -m aNameForYourStash 를 사용하여 저장합니다. 그런 다음 git stash list 를 사용하여 적용하려는 stash 의 인덱스를 학습합니다. 그런 다음 git stash pop --index 0 을 사용하여 숨김을 팝업하고 적용합니다.

참고: 저는 git 버전 2.21.0.windows.1을 사용하고 있습니다.


canbax

그래서, 나는 이 주제에 대해 왜 그렇게 많은 경악이 있는지 잘 모르겠습니다. push 와 deprecated save 둘 다로 git stash 이름을 지정할 수 있고, 정규 표현식을 사용하여 apply 되돌릴 수 있습니다.

적용할 이름을 사용하는 Git stash 메서드

 $ git stash push -m "john-hancock" $ git stash apply stash^{/john-hancock}

이전에 언급했듯이 save push 호출로 업데이트할 수 없는 이전 시스템에서 이 명령을 사용할 수 있습니다. push 명령과 달리 save -m 스위치가 필요하지 않습니다.

 // save is deprecated but still functional $ git stash save john-hancock

이것은 Git 2.2 및 Windows 10입니다.

시각적 증거

다음은 그 과정을 보여주는 아름다운 애니메이션 GIF입니다.

식별 가능한 이름을 사용하여 적용되는 git stash를 보여주는 애니메이션 GIF.

사건의 연속

GIF는 빠르게 실행되지만 살펴보면 프로세스는 다음과 같습니다.

  1. ls 명령은 디렉토리에 4개의 파일을 표시합니다.
  2. touch example.html 은 다섯 번째 파일을 추가합니다.
  3. git stash push -m "john-hancock" -a ( -a 에는 추적되지 않은 파일이 포함됨)
  4. ls 명령은 stash 뒤에 4개의 파일을 표시합니다. 이는 stash 및 암시적 하드 리셋이 작동했음을 의미합니다.
  5. git stash apply stash^{/john-hancock} 실행
  6. ls 명령은 5개의 파일을 나열하며 example.html 파일이 다시 가져와 git stash apply 명령이 작동했음을 나타냅니다.

이게 말이 되나요?

솔직히 말해서 이 접근 방식의 이점이 무엇인지 잘 모르겠습니다. stash에 이름을 지정하는 것은 가치가 있지만 검색은 아닙니다. shelve 및 unshelve 프로세스를 스크립팅하는 것이 도움이 될 수 있지만 이름으로 숨김을 팝업하는 것이 훨씬 쉽습니다.

 $ git stash pop 3 $ git stash apply 3

정규식보다 훨씬 쉬워 보입니다.


Cameron McKenzie

.zshrc 파일에는 다음 두 가지 기능이 있습니다.

 function gitstash() { git stash push -m "zsh_stash_name_$1" } function gitstashapply() { git stash apply $(git stash list | grep "zsh_stash_name_$1" | cut -d: -f1) }

다음과 같이 사용합니다.

 gitstash nice gitstashapply nice

iWheelBuy

이것은 어떻습니까?

 git stash save stashname git stash apply stash^{/stashname}

AdamB

별명

sapply = "!f() { git stash apply \"$(git stash list | awk -F: --posix -vpat=\"$*\" \"$ 0 ~ pat {print $ 1; exit}\")\"; }; f"

용법

git sapply "<regex>"

  • Windows용 Git과 호환

편집: 원래 솔루션을 고수했지만 대다수가 Etan Reisner 버전(위)을 선호하는 이유를 알았습니다. 기록을 위해:

 sapply = "!f() { git stash apply \"$(git stash list | grep -E \"$*\" | awk \"{ print $ 1; }\" | sed -n \"s/://;1p\")\"; }; f"

Vlastimil Ovčáčík

git stash apply stash^{/<regex>} 가 작동하지 않는 것은 불행한 일입니다(실제로 숨김 목록을 검색하지 않으며 허용되는 답변 아래의 주석 참조).

git stash list 을 검색하여 첫 번째(가장 최근) stash@{<n>} 를 찾은 다음 git stash <command> 전달하는 드롭인 교체입니다.

 # standalone (replace <stash_name> with your regex) (n=$(git stash list --max-count=1 --grep=<stash_name> | cut -f1 -d":") ; if [[ -n "$n" ]] ; then git stash show "$n" ; else echo "Error: No stash matches" ; return 1 ; fi) (n=$(git stash list --max-count=1 --grep=<stash_name> | cut -f1 -d":") ; if [[ -n "$n" ]] ; then git stash apply "$n" ; else echo "Error: No stash matches" ; return 1 ; fi)
 # ~/.gitconfig [alias] sshow = "!f() { n=$(git stash list --max-count=1 --grep=$1 | cut -f1 -d":") ; if [[ -n "$n" ]] ; then git stash show "$n" ; else echo "Error: No stash matches $1" ; return 1 ; fi }; f" sapply = "!f() { n=$(git stash list --max-count=1 --grep=$1 | cut -f1 -d":") ; if [[ -n "$n" ]] ; then git stash apply "$n" ; else echo "Error: No stash matches $1" ; return 1 ; fi }; f" # usage: $ git sshow my_stash myfile.txt | 1 + 1 file changed, 1 insertion(+) $ git sapply my_stash On branch master Your branch is up to date with 'origin/master'. Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: myfile.txt no changes added to commit (use "git add" and/or "git commit -a")

다른 스크립트 내에서 이러한 명령을 사용할 수 있도록 적절한 결과 코드가 반환됩니다. 다음을 사용하여 명령을 실행한 후 확인할 수 있습니다.

 echo $?

--grep=$1 부분이 확실하지 않기 때문에 변수 확장 익스플로잇에 주의하십시오. 아마도 --grep="$1" 이어야 하지만 이것이 정규식 구분 기호를 방해하는지 확실하지 않습니다(나는 제안에 열려 있습니다).


Zack Morris

이 답변은 Klemen Slavič에게 많은 빚을 졌습니다. 나는 허용 된 답변에 대해 방금 언급했지만 아직 담당자가 충분하지 않습니다 :(

git 별칭을 추가하여 숨김 참조를 찾고 표시, 적용, 삭제 등의 다른 별칭에서 사용할 수도 있습니다.

 [alias] sgrep = "!f() { ref=$(git --no-pager stash list | grep "$1" | cut -d: -f1 | head -n1); echo ${ref:-<no_match>}; }; f" sshow = "!f() { git stash show $(git sgrep "$1") -p; }; f" sapply = "!f() { git stash apply $(git sgrep "$1"); }; f" sdrop = "!f() { git stash drop $(git sgrep "$1"); }; f"

ref=$( ... ); echo ${ref:-<no_match>}; 패턴은 빈 문자열이 반환되지 않으므로 sshow, sapply 및 sdrop이 예상대로 실패하는 대신 최신 숨김을 대상으로 합니다.


Nathanael

별칭 이것은 함수로 캡슐화할 필요 없이 유닉스 계열 시스템에 대한 보다 직접적인 구문일 수 있습니다. [alias] 아래의 ~/.gitconfig에 다음을 추가합니다.

 sshow = !sh -c 'git stash show stash^{/$*} -p' - sapply = !sh -c 'git stash apply stash^{/$*}' - ssave = !sh -c 'git stash save "${1}"' -

용법: 정규식을 적용

예: git sshow MySecretStash

끝에 하이픈은 표준 입력에서 입력을 말합니다.


Rohanthewiz

작은 bash 스크립트를 사용하여 숨김 번호를 찾습니다. "gitapply"라고 부르십시오.

 NAME="$1" if [[ -z "$NAME" ]]; then echo "usage: gitapply [name]"; exit; fi git stash apply $(git stash list | grep "$NAME" | cut -d: -f1)

용법:

 gitapply foo

...여기서 foo는 원하는 숨김 이름의 하위 문자열입니다.


Will Sheppard

git stash save NAME 을 사용하여 저장하십시오.

그런 다음 ... 이 스크립트를 사용하여 적용(또는 팝)할 항목을 선택할 수 있습니다.

 #!/usr/bin/env ruby #git-stash-pick by Dan Rosenstark # can take a command, default is apply command = ARGV[0] command = "apply" if !command ARGV.clear stashes = [] stashNames = [] `git stash list`.split("\n").each_with_index { |line, index| lineSplit = line.split(": "); puts "#{index+1}. #{lineSplit[2]}" stashes[index] = lineSplit[0] stashNames[index] = lineSplit[2] } print "Choose Stash or ENTER to exit: " input = gets.chomp if input.to_i.to_s == input realIndex = input.to_i - 1 puts "\n\nDoing #{command} to #{stashNames[realIndex]}\n\n" puts `git stash #{command} #{stashes[realIndex]}` end

나는 숨김의 이름을 보고 선택할 수 있는 것을 좋아합니다. 또한 나는 Zshell을 사용하고 솔직히 위의 Bash 별칭 중 일부를 사용하는 방법을 몰랐습니다.)

참고: Kevin이 말했듯 이 대신 태그와 체리 픽을 사용해야 합니다.


Dan Rosenstark

다음은 PowerShell을 사용하여 이 작업을 수행하는 한 가지 방법입니다.

 <# .SYNOPSIS Restores (applies) a previously saved stash based on full or partial stash name. .DESCRIPTION Restores (applies) a previously saved stash based on full or partial stash name and then optionally drops the stash. Can be used regardless of whether "git stash save" was done or just "git stash". If no stash matches a message is given. If multiple stashes match a message is given along with matching stash info. .PARAMETER message A full or partial stash message name (see right side output of "git stash list"). Can also be "@stash{N}" where N is 0 based stash index. .PARAMETER drop If -drop is specified, the matching stash is dropped after being applied. .EXAMPLE Restore-Stash "Readme change" Apply-Stash MyStashName Apply-Stash MyStashName -drop Apply-Stash "stash@{0}" #> function Restore-Stash { [CmdletBinding()] [Alias("Apply-Stash")] PARAM ( [Parameter(Mandatory=$true)] $message, [switch]$drop ) $stashId = $null if ($message -match "stash@{") { $stashId = $message } if (!$stashId) { $matches = git stash list | Where-Object { $_ -match $message } if (!$matches) { Write-Warning "No stashes found with message matching '$message' - check git stash list" return } if ($matches.Count -gt 1) { Write-Warning "Found $($matches.Count) matches for '$message'. Refine message or pass 'stash{@N}' to this function or git stash apply" return $matches } $parts = $matches -split ':' $stashId = $parts[0] } git stash apply ''$stashId'' if ($drop) { git stash drop ''$stashId'' } }

자세한 내용은 여기


Geoffrey Hudik

내 생선 껍질에

 function gsap git stash list | grep ": $argv" | tr -dc '0-9' | xargs git stash apply end

사용하다

gsap name_of_stash


Matsumoto Kazuya

git stash apply stash@{0} 이외의 다른 참조에서도 작동합니다. 따라서 일반 태그 를 사용하여 영구 이름을 얻을 수 있습니다. git stash drop 또는 git stash pop 을 할 수 없다는 장점이 있습니다.

따라서 다음과 같이 별칭 pstash (일명 "영구 숨김")를 정의할 수 있습니다.

 git config --global alias.pstash '!f(){ git stash && git tag "$1" stash && git stash drop; }; f'

이제 태그가 지정된 숨김을 만들 수 있습니다.

 git pstash x-important-stuff

평소처럼 다시 show 하고 apply

 git stash show x-important-stuff git stash apply x-important-stuff

A.H.

파티에 늦었지만 VSCode를 사용하는 경우 빠른 방법은 명령 팔레트(CTRL / CMD + SHIFT + P)를 열고 "Pop Stash"를 입력하는 것입니다. 이름으로 숨김을 검색할 수 있습니다. git CLI를 사용할 필요 없이


Alexandre Gomes

여기에는 많은 답변이 있지만 OP가 추구하는 원하는 동등한 기능이 하나의 답변이나 의견으로 완전히 캡슐화되지 않았다고 생각합니다.

git add , git diff , git rm , git reset 을 사용자 지정 git 명령으로 결합하여 나중에 이름으로 쉽게 참조할 수 있는 패치 파일로 변경 사항을 빠르게 집계할 수 있습니다.

자식 병 데모

다음은 위의 사용자 지정 git 명령에 사용된 명령입니다(gist 로도 사용 가능) - 현재 분기를 재설정하고 로컬 파일에 대한 모든 변경 사항을 제거 --hard 플래그의 사용에 유의하십시오.

 #!/usr/bin/env bash if [ $# -eq 1 ] ; then NAME=$1 else echo "Please pass exactly one argument, which is the name of the patch file" exit 1 fi git add . # if previous patch file with the same name exists untrack it if [ -f "$NAME.patch" ] ; then git rm --cached $NAME.patch fi # warning: this will diff all changes into a file called NAME.patch and do a hard reset of the current branch git diff --staged > $NAME.patch git reset --hard $HEAD
  • 이제 git bottle hello 를 실행하여 hello.patch 파일을 생성할 수 있습니다.
  • git apply hello.patch

트릭은 diff 명령 의 준비된(또는 캐시된) 옵션 을 활용할 수 있도록 먼저 모든 파일을 추적하는 것입니다. 약간의 조정을 통해 사용자 지정 명령을 확장하여 작업 디렉토리 외부, 즉 하드 드라이브의 일부 Patches 폴더에 있는 패치 파일을 출력하거나 .gitignore 파일을 업데이트하여 무시할 수 있습니다.

기한이 있는 크레딧: 이 답변 은 패치 접근 방식을 설명하는 내 답변에 영감을 주었지만 새 파일의 변경 사항은 diff 디스플레이에서 제외된다는 언급을 무시했습니다.

주의 사항: 이 명령은 git add 의존하기 때문에 git이 이미 무시하고 있는 파일의 변경 사항을 병에 넣지 않습니다.


GrayedFox

나는 그 이름으로 숨김을 git pop하는 방법이 없다고 생각합니다.

나는 그것을하는 bash 함수를 만들었습니다.

 #!/bin/bash function gstashpop { IFS=" " [ -z "$1" ] && { echo "provide a stash name"; return; } index=$(git stash list | grep -e ': '"$1"'$' | cut -f1 -d:) [ "" == "$index" ] && { echo "stash name $1 not found"; return; } git stash apply "$index" }

사용 예:

 [~/code/site] on master* $ git stash push -m"here the stash name" Saved working directory and index state On master: here the stash name [~/code/site] on master $ git stash list stash@{0}: On master: here the stash name [~/code/site] on master $ gstashpop "here the stash name"

도움이 되기를 바랍니다!


franzisk

숨김 생성 이외의 모든 것에 대해 fzf 를 종속성으로 도입하여 다른 솔루션을 제안합니다. 5분의 시간을 할애하고 소개를 받는 것이 좋습니다. 이는 전반적으로 생산성을 크게 향상시켜 주기 때문입니다.

어쨌든, 숨김 검색을 제공하는 예제 페이지 에서 관련 발췌. 추가 기능(예: 응용 프로그램 숨김 또는 삭제)을 추가하기 위해 스크립틀릿을 변경하는 것은 매우 쉽습니다.

 fstash() { local out qk sha while out=$( git stash list --pretty="%C(yellow)%h %>(14)%Cgreen%cr %C(blue)%gs" | fzf --ansi --no-sort --query="$q" --print-query \ --expect=ctrl-d,ctrl-b); do mapfile -t out <<< "$out" q="${out[0]}" k="${out[1]}" sha="${out[-1]}" sha="${sha%% *}" [[ -z "$sha" ]] && continue if [[ "$k" == 'ctrl-d' ]]; then git diff $sha elif [[ "$k" == 'ctrl-b' ]]; then git stash branch "stash-$sha" $sha break; else git stash show -p $sha fi done }

laur

이것은 내가 만든 빠른 설정이며 저를 위해 작동합니다. 귀하에게도 효과가 있기를 바랍니다.

내 package.json 프로젝트 파일에 원격 저장소에 푸시하고 싶지 않은 사용자 정의/로컬 스크립트가 있다고 가정해 보겠습니다.

 { // ... package.json stuff "scripts": { "custom": "ts-node a_ts_test_file.ts" } }

그래서 나는 내 브랜치를 푸시하고 다음 "git push"까지 숨김을 팝하고 싶을 때 이 변경 사항을 숨기기로 결정했습니다.

그래서 ...

  1. 새 git 별칭을 만들어야 합니다.
 # dev is the "stash tag" # To stash current working directory git config --global alias.sh "stash -m 'dev'"
  1. zsh 또는 oh-my-zsh를 사용하는 경우 ~.bashrz 또는 ~.zshrc 를 편집해야 합니다. 다음 별칭을 추가합니다.
 # Apply stash "tagged" $(X) where X is substring of "git stash list" output filtered by output that contains "dev". # I didn't use git stash apply because "dev" tag isn't unique, so it's a need to pop the stash and ensure to create a new one alias set on first step alias gitsh="git stash pop $(git stash list | grep 'dev' | cut -d ':' -f 1) || echo 'nope'"
  1. 즐기다

"dev" 태그가 있는 작업 디렉토리를 푸시하려면: git sh "dev" 태그가 지정된 stash에서 변경된 변경 사항을 가져 sitsh

(내가 5분 만에 만든 작은 스크립트이며 실패하면 ... 수정하십시오! )


Luis Danilo

출처 : http:www.stackoverflow.com/questions/11269256/how-to-name-and-retrieve-a-stash-by-name-in-git

반응형