Skip to content

Commit

Permalink
added open command
Browse files Browse the repository at this point in the history
  • Loading branch information
geoffrey1330 committed Jun 25, 2023
1 parent 2c7df3c commit 642f9b4
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
7 changes: 7 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ func main() {
fmt.Fprintf(os.Stderr, " copy <srcfile> <destfile> Copy a file to a new location\n")
fmt.Fprintf(os.Stderr, " move <srcfile> <destfile> Move a file to a new location\n")
fmt.Fprintf(os.Stderr, " search <directory> <filename> Search for a file in a directory\n")
fmt.Fprintf(os.Stderr, " open <filename> Open a file in the default editor\n")
fmt.Fprintf(os.Stderr, "\nOptions:\n")
flag.PrintDefaults()
}
Expand Down Expand Up @@ -89,6 +90,12 @@ func main() {
return
}
searchFiles(args[1], args[2])
case "open":
if len(args) < 2 {
fmt.Println("Usage: filecommander open <filename>")
return
}
openFile(args[1])
default:
fmt.Println("Invalid command:", command)
}
Expand Down
57 changes: 57 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
)

func createFile(filename string) {
Expand Down Expand Up @@ -122,3 +124,58 @@ func moveFile(src, dest string) {

fmt.Println("File moved from", src, "to", dest)
}

func openFile(filename string) error {
if err := verifyCodeCommand(); err != nil {
return err
}

var cmd *exec.Cmd

if runtime.GOOS == "windows" {
// On Windows, use "code.cmd"
cmd = exec.Command("code.cmd", filename)
} else {
cmd = exec.Command("code", filename)
}

err := cmd.Start()
if err != nil {
return err
}

return nil
}

func verifyCodeCommand() error {
_, err := exec.LookPath("code")
if err != nil {
fmt.Println("code command not found. Attempting to install...")
err = installCodeCommand()
if err != nil {
return fmt.Errorf("failed to verify and install code command: %s", err)
}
fmt.Println("code command installed successfully.")
}
return nil
}

func installCodeCommand() error {
var command string
var args []string
if runtime.GOOS == "windows" {
command = "powershell"
args = []string{"-Command", "& { Invoke-WebRequest -Uri 'https://go.microsoft.com/fwlink/?LinkID=760868' -OutFile 'vscode.zip' }"}
} else {
command = "bash"
args = []string{"-c", "curl -o vscode.zip -L https://go.microsoft.com/fwlink/?LinkID=760868 && unzip vscode.zip && sudo mv 'VSCode.app' '/usr/local/bin/code'"}
}

cmd := exec.Command(command, args...)
err := cmd.Run()
if err != nil {
return fmt.Errorf("failed to install code command: %s", err)
}

return nil
}

0 comments on commit 642f9b4

Please sign in to comment.