बैश / zsh फ़ंक्शन जो कि जीट ट्री की जड़ को सीडी करता है
Nov 26 2020
मैं फ़ंक्शन के लिए एक समीक्षा प्राप्त करना चाहता हूं जो कि git ट्री रूट में cd है या कुछ भी नहीं है अगर हम रिपॉजिटरी के बाहर हैं।
समीक्षा किए गए संस्करण:
# cd to the root of the current git directory
# If $PWD is submodule, will cd to the root of the top ancestor # It requires to stay in the current directory, if the root is . or unknown, # and use cd only once, to have a way to do `cd -` function cg { git_root() { local super_root local top top="$(git rev-parse --show-cdup)"
top="${top:-./}" super_root="$(git rev-parse --show-superproject-working-tree)"
if [[ "$super_root" ]]; then printf '%s' "$top../"
( cd "$top../" && git_root || return ) fi printf '%s' "$top"
}
local git_root
git_root="$(git_root)" [ "x${git_root}" != "x./" ] && cd "$(git_root)" && return || return 0
}
अपडेट किया गया वर्ज़न:
#!/bin/bash
# cd to the root of the current git directory
# If $PWD is submodule, will cd to the root of the top ancestor
# It requires to stay in the current directory, if the root is . or unknown,
# and use cd only once, to have a way to do `cd -`
function cg {
function git_root {
local top; top="$(git rev-parse --show-cdup)" top="${top:-./}"
local super_root; super_root="$(git rev-parse --show-superproject-working-tree)" if [[ "$super_root" ]]; then
printf '%s' "$top../" ( cd "$top../" && git_root || return )
fi
printf '%s' "$top" } local tree_root tree_root="$(git_root)"
[[ "x${tree_root}" != "x./" ]] && cd "${tree_root}" && return || return 0
}
जवाब
4 chicks Nov 26 2020 at 10:12
महान
- शेलचेक पर 100% पास जिसका मतलब है कि आप हर उस चीज को उद्धृत कर रहे हैं जो संभावित रूप से समस्याग्रस्त हो सकती है।
- स्कूपिंग वैरिएबल
- के
[[लिए सशर्त का उपयोग करनाif - यह क्या कर रहा है और क्यों की अच्छी व्याख्या
बेहतर हो सकता था
- शीर्ष पर एक श-बैंग लाइन लिपियों के लिए एक अच्छा विचार है, भले ही यह आमतौर पर आपकी लॉगिन स्क्रिप्ट के दौरान खट्टा हो।
- आपके आंतरिक फ़ंक्शन को आपके बाहरी फ़ंक्शन की तुलना में अलग सिंटैक्स के साथ परिभाषित किया गया है।
- आप एक लाइन में एक चर को गुंजाइश और परिभाषित कर सकते हैं। उदाहरण के लिए
local super_root="$(git rev-parse --show-superproject-working-tree)":। यह सुनिश्चित करता है कि आप एक स्थानीय चर को परिभाषित करने में विफल नहीं होते हैं या एक नए चर को स्कोप करने में विफल होते हैं। और यह प्रत्येक मामले में कोड की एक पंक्ति को काटता है। git_rootएक चर नाम और फ़ंक्शन नाम के लिए पुन: उपयोग करना भ्रमित कर रहा है। मैंने शुरू में सोचा था कि आप इसे परिभाषित करने के बाद समारोह को सीमित करने की कोशिश क्यों कर रहे थे।[[अंतिम पंक्ति में सशर्त के लिए सशर्त का उपयोग करें ।