Skip to content

Commit

Permalink
#15 add: also allow storing of multi-line commands in Atuin
Browse files Browse the repository at this point in the history
Signed-off-by: Patrizio Bekerle <[email protected]>
  • Loading branch information
pbek committed Oct 5, 2024
1 parent 4fb5e85 commit aed4551
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# QOwnNotes command-line snippet manager changelog

## v0.6.1
- The `--atuin` flag now also add commands to [Atuin](https://atuin.sh/) for multi-line commands
(for [#15](https://github.com/qownnotes/qc/issues/15))
- The `--color` flag now shows the command description in a calmer green, instead of red
(for [#16](https://github.com/qownnotes/qc/issues/16))

Expand Down
25 changes: 20 additions & 5 deletions cmd/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"log"
"os"
"path/filepath"
"strconv"
"strings"

"github.com/fatih/color"
Expand Down Expand Up @@ -68,16 +67,32 @@ func execute(cmd *cobra.Command, args []string) (err error) {
writeLastCmdFile(command)
}

// Check if the command has only a single line
if config.Flag.Atuin && !strings.Contains(command, "\n") {
escapedCommand := strconv.Quote(command)
command = `histid=$(atuin history start -- ` + escapedCommand + ")\n" + command +
// Add commands to the Atuin history
if config.Flag.Atuin {
escapedCommand := escapeCommandForShell(command)
command = `histid=$(atuin history start -- ` + escapedCommand + `` + ")\n" + command +
"\natuin history end --exit $? $histid"
}

return run(command, os.Stdin, os.Stdout)
}

// escapeCommandForShell escapes a command for use in a shell script.
// It also works for multi-line commands.
func escapeCommandForShell(command string) string {
// Trim and split the command into lines
lines := strings.Split(strings.Trim(command, "\n"), "\n")

// Quote each line individually and join with literal $'\n'
quotedLines := make([]string, len(lines))
for i, line := range lines {
// Use single quotes to avoid most escaping issues
quotedLines[i] = "'" + strings.ReplaceAll(line, "'", "'\"'\"'") + "'"
}

return strings.Join(quotedLines, "$'\\n'")
}

func init() {
RootCmd.AddCommand(execCmd)
execCmd.Flags().BoolVarP(&config.Flag.Color, "color", "", false,
Expand Down

0 comments on commit aed4551

Please sign in to comment.