dotfiles/nushell/config/gclone.nu

142 lines
3.9 KiB
Plaintext

# gclone aliases
def _gclone_dirs [] {
_ls ($env.GCLONE_PATH + "/*")
| append (_ls ($env.GCLONE_PATH + "/*/*"))
| append (_ls ($env.GCLONE_PATH + "/*/*/*"))
| each { $in.name | path basename }
| sort
| uniq
}
# cd to a git directory
def --env cdg [key: string@_gclone_dirs] {
let dir = _ls ($env.GCLONE_PATH + "/*")
| append (_ls ($env.GCLONE_PATH + "/*/*"))
| append (_ls ($env.GCLONE_PATH + "/*/*/*"))
| where { $in != null and ($in.name | path basename) == $key }
match ($dir | length) {
0 => {
print (
(ansi red_bold) + "error" +
(ansi reset) + (ansi attr_bold) + ":" +
(ansi reset) + " no such file or directory"
)
return
}
1 => {
cd $dir.0.name
}
_ => {
print (
(ansi attr_bold) + "info:" +
(ansi reset) + " multiple entries found, please select one"
)
echo $dir
print (
(ansi --escape 'A') +
(ansi attr_bold) + "Enter your choice: " + (ansi reset)
)
let choice = input
if not ($choice =~ "^[0-9]*$") {
print (
(ansi red_bold) + "error" +
(ansi reset) + (ansi attr_bold) + ":" +
(ansi reset) + " couldn't parse integer"
)
return
}
let choice = $choice | into int
if $choice >= ($dir | length) {
print (
(ansi red_bold) + "error" +
(ansi reset) + (ansi attr_bold) + ":" +
(ansi reset) + " integer is outside range"
)
return
}
cd ($dir | get $choice | get name)
}
}
}
# clone repository in the right place
def gclone [repo_url: string] {
let attr = if ($repo_url | str starts-with "https://") {
$repo_url | parse "https://{server}/{owner}/{repo}" | get 0
} else if ($repo_url | str starts-with "http://") {
$repo_url | parse "http://{server}/{owner}/{repo}" | get 0
} else if ($repo_url | str starts-with "ssh://") {
$repo_url | parse "ssh://git@{server}/{owner}/{repo}" | get 0
} else if ($repo_url | str starts-with "git@") {
$repo_url | parse "git@{server}:{owner}/{repo}" | get 0
} else {
print (
(ansi red_bold) + "error" +
(ansi reset) + (ansi attr_bold) + ":" +
(ansi reset) + " failed to parse repo url"
)
return
}
let server = $attr.server
let server_portless = $attr.server | split row ':' | get 0
let owner = $attr.owner
let repo = $attr.repo
let target = [$env.GCLONE_PATH, $server_portless, $owner, $repo] | path join
let target = if ($target | str ends-with '.git') {
$target | path parse | update extension "" | get parent stem | str join "/"
} else {
$target
}
if ($target | path exists) {
print (
(ansi red_bold) + "error" +
(ansi reset) + (ansi attr_bold) + ":" +
(ansi reset) + " clone target already exists"
)
return
}
let clone_url = if $env.GCLONE_FORCE_SSH {
$attr | format "ssh://git@{server}/{owner}/{repo}"
} else {
$repo_url
}
print -n (
(ansi attr_bold) + "info:" +
(ansi reset) + " cloning " + $clone_url + "..."
)
let clone = do { git clone --recurse-submodules $clone_url $target } | complete
if $clone.exit_code == 0 {
print " done!"
} else {
print (
"\n" + (ansi red_bold) + "error" +
(ansi reset) + (ansi attr_bold) + ":" +
(ansi reset) + " clone failed:"
)
print -n $clone.stderr
}
}