From f3a25087985bff2c7589f66acdd64ab6bc034ed3 Mon Sep 17 00:00:00 2001 From: lixulun Date: Fri, 12 Jun 2026 15:34:37 +0800 Subject: [PATCH] generating "," instead of keeping it in repository --- , | 14 -------------- .gitignore | 1 + main.go | 31 +++++++++++++++++++++++++++++++ readme.md | 20 ++++++++++++++++++-- 4 files changed, 50 insertions(+), 16 deletions(-) delete mode 100755 , diff --git a/, b/, deleted file mode 100755 index b764dd7..0000000 --- a/, +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh - -script_path=$(realpath $0) -script_dir=$(dirname $script_path) - -cd $script_dir - -output=/tmp/commandgo - -# 为什么不直接使用 go run . 呢 -# 因为 go run 编译时会往 PATH 里注入 Go 的 bin 目录,这个修改过后的 PATH 会传递给子进程 -# 于是程序运行起来时获取的 PATH 环境变量和外界不一致,因此不用 go run . 编译运行 -go build -o $output . && $output $@ - diff --git a/.gitignore b/.gitignore index b25c15b..0862e81 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ +, *~ diff --git a/main.go b/main.go index 32aaaa1..98fc27f 100644 --- a/main.go +++ b/main.go @@ -1,10 +1,29 @@ package main import ( + "errors" "fmt" "os" ) +var commaSh = `#!/bin/sh + +script_path=$(realpath $0) +script_dir=$(dirname $script_path) + +cd $script_dir + +output=/tmp/commandgo + +# why not just using "go run ." ? +# Because "go run ." will inject GOBIN into PATH while compiling, +# and modifed PATH will pass into actual program. +# So the program doesn't have the same PATH as outside. +# It's not a acceptable behavior. + +go build -o $output . && $output $@ +` + func commandsUsage() string { return fmt.Sprintf( `commands: @@ -13,6 +32,18 @@ func commandsUsage() string { } func main() { + pwd, err := os.Getwd() + if err != nil { + panic(fmt.Errorf("detect current directory failed! %w", err)) + } + target := pwd + string(os.PathSeparator) + "," + _, err = os.Stat(target) + if errors.Is(err, os.ErrNotExist) { + err := os.WriteFile(target, []byte(commaSh), 0755) + if err != nil { + panic(fmt.Errorf("write sh failed: %w", err)) + } + } if len(os.Args) >= 2 { switch os.Args[1] { case "path": diff --git a/readme.md b/readme.md index 36e15bb..8d94a6a 100644 --- a/readme.md +++ b/readme.md @@ -2,5 +2,21 @@ Personal tools set written in Golang. -To use it just clone and add the directory to *PATH*. -Then type "," command, all commands will appear. +## How to run + +0. Clone this repository to somewhere +0. Add the root directory to *PATH* +0. change directory to the root directory +0. Run `go run .` to generate "," command +0. Run "," command to see all commands + +"," command can auto rebuild if you change the code in this repository. +Actually it always builds each time you type it! Because `go build` is +very fast and it has cache, it's not a problem in terms of speed. + +## Q&A + +Q: Why generating "," shell script instead of putting it in repository? + +A: I like the repository keeps 100% Go source code. I tried writting "," +shell script as a Go source code with shebang, but it didn't work.