Skip to content

Commit

Permalink
修复pager=more的问题; 修复--update时文件权限问题; build脚本优化
Browse files Browse the repository at this point in the history
  • Loading branch information
Karmenzind committed Dec 30, 2023
1 parent 8d2a877 commit 97b2a2f
Show file tree
Hide file tree
Showing 8 changed files with 169 additions and 99 deletions.
16 changes: 8 additions & 8 deletions .github/workflows/release-tags.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ jobs:
steps:
- uses: actions/checkout@v3

- name: "Build Changelog"
id: build_changelog
uses: mikepenz/release-changelog-builder-action@v4
env:
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
with:
commitMode: true

- name: Set up Go
uses: actions/setup-go@v4
with:
Expand All @@ -38,14 +46,6 @@ jobs:
bash scripts/build.sh linux arm64
bash scripts/build.sh windows amd64
- name: "Build Changelog"
id: build_changelog
uses: mikepenz/release-changelog-builder-action@v4
env:
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
with:
commitMode: true

- name: echo changelog
run: echo ${{steps.build_changelog.outputs.changelog}}

Expand Down
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,17 @@
sudo sh -c 'curl --create-dirs -L -o /usr/local/bin/kd <URL> && chmod +x /usr/local/bin/kd'
```

<!-- sudo sh -c 'curl --create-dirs -L -o /usr/local/bin/kd https://github.com/Karmenzind/kd/releases/latest/download/kd_macos_arm64 && chmod +x /usr/local/bin/kd' -->
<!-- ArchLinux推荐通过AUR一键安装`yay -S aur/kd`,后续直接通过包管理升级 -->

### Windows

用Powershell执行:

```powershell
# 下载文件放入C:\bin
Invoke-WebRequest -uri '<URL>' -OutFile ( New-Item -Path "C:\bin\kd.exe" -Force )
# 下载文件放入C:\bin,这里是Win64位架构,其他架构需求请提交issue
Invoke-WebRequest -uri 'https://github.com/Karmenzind/kd/releases/latest/download/kd_windows_amd64.exe' -OutFile ( New-Item -Path "C:\bin\kd.exe" -Force )
# (需要管理员权限)将C:\bin加入PATH环境变量
[Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\bin", "Machine")
```
Expand Down Expand Up @@ -126,7 +128,7 @@ GLOBAL OPTIONS:
```toml
# 是否使用分页器,MacOS上默认false
paging = true
# 分页器命令,例如:less -F / bat / more
# 分页器命令,例如:less -F / bat / more -e
pager_command = "less -F"

# 本地最多缓存的单词条数
Expand Down
1 change: 1 addition & 0 deletions cmd/kd.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ func flagStatus(*cli.Context, bool) error {
fmt.Printf(" Daemon PID:%d\n", di.PID)
fmt.Printf(" 配置文件地址:%s\n", config.CONFIG_PATH)
fmt.Printf(" 数据文件目录:%s\n", cache.CACHE_ROOT_PATH)
fmt.Printf(" Log地址:%s\n", logger.LOG_FILE)
kdpath, err := pkg.GetExecutablePath()
if err == nil {
fmt.Printf(" Binary地址:%s\n", kdpath)
Expand Down
96 changes: 66 additions & 30 deletions internal/update/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
Expand All @@ -20,6 +21,7 @@ import (
"go.uber.org/zap"
)

// var LATEST_RELEASE_URL = "http://localhost:8901/"
var LATEST_RELEASE_URL = "https://github.com/Karmenzind/kd/releases/latest/download/"
var TAGLIST_URL = "https://api.github.com/repos/Karmenzind/kd/tags"

Expand Down Expand Up @@ -122,39 +124,73 @@ func GetNewerVersion(currentTag string) (tag string, err error) {
}

func UpdateBinary(currentTag string) (err error) {
_ = currentTag
// emoji.Println(":eyes: 不好意思更新功能没写好,请手动到release下载")
tmpPath := filepath.Join(cache.CACHE_ROOT_PATH, "kd.temp")
url := getBinaryURL()

var exepath string
exepath, err = pkg.GetExecutablePath()
if err != nil {
return err
}
if strings.Contains(exepath, "go-build") {
fmt.Println("非binary,已忽略")
return nil
}

d.EchoRun(fmt.Sprintf("Start downloading: %s", url))
err = pkg.DownloadFile(tmpPath, url)
if err != nil {
zap.S().Errorf("Failed to download binary file: %s", err)
}
d.EchoRun("已下载完成")
err = os.Rename(tmpPath, exepath)
d.EchoRun("已成功覆盖")
if err != nil {
return err
}
if runtime.GOOS != "windows" {
err = pkg.AddExecutablePermission(exepath)
if err != nil {
d.EchoWrong(fmt.Sprintf("修改权限失败,请手动执行`chmod +x %s`", exepath))
}
}
tmpPath := filepath.Join(cache.CACHE_ROOT_PATH, "kd.temp")
url := getBinaryURL()

var exepath string
exepath, err = pkg.GetExecutablePath()
if err != nil {
return err
}
if strings.Contains(exepath, "go-build") {
fmt.Println("非binary,已忽略")
return nil
}

d.EchoRun(fmt.Sprintf("Start downloading: %s", url))
// TODO (k): <2023-12-31> 调用curl
err = pkg.DownloadFile(tmpPath, url)
if err != nil {
zap.S().Errorf("Failed to download binary file: %s", err)
}
d.EchoRun("已下载完成")
err = moveFile(tmpPath, exepath)
if err != nil {
return
} else {
d.EchoRun("已成功覆盖")
}
if runtime.GOOS != "windows" {
err = pkg.AddExecutablePermission(exepath)
if err != nil {
d.EchoWrong(fmt.Sprintf("修改权限失败,请手动执行`chmod +x %s`", exepath))
}
}
return
// emoji.Println(":lightning: Now we start updating the binary")
// emoji.Println(":lightning: updating...")
// emoji.Println(":beer: DONE :)")
}

// try sudo if needed
func moveFile(src, tgt string) (err error) {
err = os.Rename(src, tgt)
if err == nil {
return
}
zap.S().Infof("Permission denied. Please make sure you have write access to the destination directory.")
if runtime.GOOS == "windows" {
return fmt.Errorf("文件覆盖失败,遇到权限问题,请到release页面下载")
}

cmd := exec.Command("sudo", "mv", src, tgt)
cmd.Stdin = os.Stdin
d.EchoRun("覆盖文件需root权限,请输入密码")
err = cmd.Run()
// if linkErr, ok := err.(*os.LinkError); ok {
// if os.IsPermission(linkErr.Err) {
// zap.S().Infof("Permission denied. Please make sure you have write access to the destination directory.")
// if runtime.GOOS == "windows" {
// return fmt.Errorf("文件覆盖失败,遇到权限问题,请到release页面下载")
// }

// cmd := exec.Command("sudo", "mv", src, tgt)
// cmd.Stdin = os.Stdin
// d.EchoRun("覆盖文件需root权限,请输入密码")
// err = cmd.Run()
// }
// }
return
}
7 changes: 5 additions & 2 deletions logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"go.uber.org/zap"
)

var LOG_FILE string

func buildLogger(logCfg *config.LoggerConfig, options ...zap.Option) (*zap.Logger, error) {
cfg := zap.NewDevelopmentConfig()
var f string
Expand All @@ -19,8 +21,8 @@ func buildLogger(logCfg *config.LoggerConfig, options ...zap.Option) (*zap.Logge
if err != nil {
f = filepath.Join(os.TempDir(), "kd.log")
} else {
name := strings.ReplaceAll(u.Username, " ", "_")
name = strings.ReplaceAll(name, "\\", "_")
name := strings.ReplaceAll(u.Username, " ", "_")
name = strings.ReplaceAll(name, "\\", "_")
f = filepath.Join(os.TempDir(), fmt.Sprintf("kd_%s.log", name))
}
} else {
Expand All @@ -29,6 +31,7 @@ func buildLogger(logCfg *config.LoggerConfig, options ...zap.Option) (*zap.Logge
if _, err := os.Stat(f); err == nil {
os.Chmod(f, 0o666)
}
LOG_FILE = f

cfg.OutputPaths = []string{f}
cfg.ErrorOutputPaths = []string{f}
Expand Down
36 changes: 32 additions & 4 deletions pkg/terminal.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,12 @@ func GetExecutableBasename() (string, error) {
// pager or print
// config > $PAGER > less -f
// TODO 增加检测pager可用
func OutputResult(out string, paging bool, pagerCmd string, clear bool) error {
func OutputResult(out string, paging bool, pagerCmd string, doClear bool) error {
var err error
var logger = zap.S()
if paging {
if pagerCmd == "" {
// XXX (k): <2023-12-31> expandenv?
if sysPager := os.Getenv("PAGER"); sysPager != "" {
logger.Debugf("Using system pager %s", sysPager)
pagerCmd = sysPager
Expand All @@ -80,15 +81,17 @@ func OutputResult(out string, paging bool, pagerCmd string, clear bool) error {
pager = exec.Command(pagerCmd)
}
if CommandExists(program) {
pager.Stdin = strings.NewReader(out)
// pager.Stdin = strings.NewReader(out)
pager.Stdout = os.Stdout
err = pager.Run()
pager.Stderr = os.Stderr
err = Output2PagerVer2(pager, out)
// err = pager.Run()
return err
}
d.EchoWarn(fmt.Sprintf("pager command `%s` not found", program))
}
}
if clear {
if doClear {
_, h, err := GetTermSize()
if err == nil && strings.Count(out, "\n") < h {
ClearScreen()
Expand All @@ -98,6 +101,31 @@ func OutputResult(out string, paging bool, pagerCmd string, clear bool) error {
return nil
}

func Output2PagerVer1(pager *exec.Cmd, output string) (err error) {
pager.Stdin = strings.NewReader(output)
err = pager.Run()

return err
}

func Output2PagerVer2(pager *exec.Cmd, output string) (err error) {
pipe, err := pager.StdinPipe()
if err != nil {
return
}

if err = pager.Start(); err != nil {
return err
}

defer func() {
pipe.Close()
pager.Wait()
}()
fmt.Fprintln(pipe, output)
return err
}

func CommandExists(cmd string) bool {
_, err := exec.LookPath(cmd)
return err == nil
Expand Down
13 changes: 5 additions & 8 deletions plan.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
#master plan

## wip
- mac编译
- 测试mac的DB初始化情况
- powershell命令改成当前用户范围
- 测试windows的--update

Expand All @@ -23,6 +21,7 @@
- 加入词库设置,供选择词库大小

## low priority
- --update下载之后缓存,避免重复下载
- cli替换为cobra
- source数据 分为base-sourse & web-source
- 刷数据,去掉音标[]
Expand All @@ -34,16 +33,13 @@

# BUG

## Build failed

mac arm64 / amd64

(action) linux 386
provide: see also

## Risk
- 实际文件名 不改的时候的process_name

# Others
## low priority
- (action) linux 386

## 写入release介绍

Expand All @@ -56,3 +52,4 @@ mac arm64 / amd64
如果没有你所使用的平台/架构,请提交issue反馈

如果下载受阻,请前往gitee备份页面

0 comments on commit 97b2a2f

Please sign in to comment.