编辑命令行提示符 prompt,支持显示 git 分支、标签等信息

实时在 Linhieng/current--Microsoft.PowerShell_profile.ps1 上更新

打开 $Profile 文件,将下面内容粘贴到其中即可:

powershell 复制代码
<# 负责打印 git 分支相关信息
    支持输出以下信息:
        当前分支,或者是 hash 值
        当前目录是否为 git 子目录
        当前是否有提交历史
#>
function write_host_git_branch {
    # 在这里,能确保是一个 git 仓库,或者是一个 git 仓库中的子目录


    # 获取当前 HEAD 所在分支名。如果当前是 detached HEAD 状态,则显示为 hash。
    $git_branch = git symbolic-ref --short --quiet HEAD
    Write-Host "(" -ForegroundColor "DarkGray" -NoNewline
    if ( $null -eq $git_branch ) {
        $hash = git rev-parse --short HEAD
        Write-Host $hash -ForegroundColor "red" -NoNewline
    } else {
        Write-Host $git_branch -ForegroundColor "blue" -NoNewline
    }
    Write-Host ") " -ForegroundColor "DarkGray" -NoNewline


    if (
        # 如果当前目录没有 .git 文件夹,说明当前是在 git 仓库的子目录
        $false -eq (Test-Path .git)
    ) {
        Write-Host "sub " -ForegroundColor "DarkGray" -NoNewline
    }



    $git_log = git log 2>&1
    if (
        # 命令执行失败
        $? -eq $false
    ) {
        write_host_not_commits($git_log)
    }


    $tags = git tag --points-at HEAD
    if (
        $null -ne $tags
    ) {
        $tags_one_line =  ($tags -split '\r?\n') -join ', '
        Write-Host "[" -ForegroundColor "DarkGray" -NoNewline
        Write-Host "$tags_one_line" -ForegroundColor "DarkYellow" -NoNewline
        Write-Host "] " -ForegroundColor "DarkGray" -NoNewline
    }


    # 打印子模块相关信息会有性能问题
    # $submodule = git submodule status 2>&1
}

function write_host_not_commits($git_log) {
    $error_message = ($git_log.Exception.Message | Select-Object -First 1).Trim()
    if (
        $true -eq $error_message.EndsWith("does not have any commits yet")
    ) {
        Write-Host "not commits yet"  -ForegroundColor "red" -NoNewline
    } else {
        Write-Host "❌fatal: $error_message" -ForegroundColor "red" -NoNewline
    }
    return
}

function wirte_host_git_wrong($git_output) {
    # 转换为字符串对象,并只获取第一行的内容
    $error_message = ($git_output.Exception.Message | Select-Object -First 1).Trim()

    # 检查输出是否以指定的前缀开头
    if (
        # 空(非 git 仓库)
        $true -eq $error_message.StartsWith("fatal: not a git repository")
    ) {
        Write-Host "" -NoNewline
    } elseif (
        # 不安全的仓库
        $true -eq $error_message.StartsWith("fatal: detected dubious ownership")
    ) {
        Write-Host "❌fatal: detected dubious ownership" -ForegroundColor "red" -NoNewline
    } else {
        Write-Host "❌fatal: $error_message" -ForegroundColor "red" -NoNewline
    }
}

function write_host_git_info {

    # 执行 Git 命令并捕获输出。 2>&1 表示将 stderr 重定向到 stdout, 以将错误信息保存在 $git_output 变量中
    $git_output = git rev-parse --is-inside-work-tree 2>&1

    if (
        # 前一个命令执行失败
        $? -eq $false
    ) {
        wirte_host_git_wrong($git_output)
        return
    }

    write_host_git_branch
}

# 判断当前是否是管理员
function has_admin_power {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = [Security.Principal.WindowsPrincipal] $identity
    $adminRole = [Security.Principal.WindowsBuiltInRole]::Administrator
    return $principal.IsInRole($adminRole)
}

function __prompt {
    # 空格原则:输出内容时,不需要考虑给前面留空,只需要考虑给后面留空

    $pwsh_version = "PS$($Host.version.Major) "
    $fullpath = "$($executionContext.SessionState.Path.CurrentLocation)"

    Write-Host "`n$pwsh_version" -NoNewline
    Write-Host "$fullpath " -NoNewline -ForegroundColor "green"

    write_host_git_info

    if (has_admin_power) {
        return "`n# "
    } else {
        return "`n$ "
    }

}

# 主入口
function prompt {
    # 编写的代码可能报错
    try {
        __prompt
        return
    } catch {
        # 输出报错信息
        Write-Host "powershell script error occurred: $_" -NoNewline -ForegroundColor "red"
    }

    return "`nPS> "
}

# 解决终端的中文乱码问题。注意,chcp 无效!
$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding
# 设置 UpArrow 快捷方式为向前搜索
Set-PSReadLineKeyHandler -Key UpArrow -ScriptBlock {
  [Microsoft.PowerShell.PSConsoleReadLine]::HistorySearchBackward()
  [Microsoft.PowerShell.PSConsoleReadLine]::EndOfLine()
} # 设置向上键为后向搜索历史记录
# 设置 DownArrow 快捷方式为向后搜索
Set-PSReadLineKeyHandler -Key DownArrow -ScriptBlock {
  [Microsoft.PowerShell.PSConsoleReadLine]::HistorySearchForward()
  [Microsoft.PowerShell.PSConsoleReadLine]::EndOfLine()
}
相关推荐
生瓜硬劈..2 小时前
从写入到可查:Elasticsearch “近实时”查询原理详解
大数据·elasticsearch·搜索引擎
Elasticsearch5 小时前
使用 Elasticsearch 和神经模型为复杂语言提供更好的文本分析
elasticsearch
Elastic 中国社区官方博客6 小时前
Elasticsearch 9.3 增加 bfloat16 向量 支持
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
XLYcmy6 小时前
智能体大赛 核心功能 惊喜生成”——创新灵感的催化器
数据库·ai·llm·prompt·agent·检索·万方
Elastic 中国社区官方博客6 小时前
Elasticsearch 用于词形还原的开源 Hebrew 分析器
大数据·elasticsearch·搜索引擎·ai·开源·全文检索·中文分词
键盘鼓手苏苏1 天前
Flutter for OpenHarmony:git 纯 Dart 实现的 Git 操作库(在应用内实现版本控制) 深度解析与鸿蒙适配指南
开发语言·git·flutter·华为·rust·自动化·harmonyos
没有bug.的程序员1 天前
Git 高级进阶:分支管理模型内核、Rebase 物理重塑与版本控制协作深度实战指南
java·git·分支管理·版本控制·rebase
秃了也弱了。1 天前
elasticSearch之API:基础命令及文档基本操作
大数据·elasticsearch·搜索引擎
一苓二肆1 天前
Git 常用指令总结(工程实战版)
大数据·git·elasticsearch
1688red1 天前
利用Logstash将MySQL/MairaDB 数据导入或同步到 Elasticsearch
大数据·elasticsearch·搜索引擎