Skip to content

Commit

Permalink
Merge pull request #10 from guonaihong/env
Browse files Browse the repository at this point in the history
env: done
  • Loading branch information
guonaihong authored Jun 13, 2019
2 parents 614e8f4 + e0380b7 commit 0372a04
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ If you want to use the cat command
* dirname [detail](./dirname/README.md)
* echo [detail](./echo/README.md)
* head [detail](./head/README.md)
* env
* link
* md5sum [detail](./md5sum/README.md)
* paste [detail](./paste/README.md)
Expand All @@ -62,4 +63,4 @@ If you want to use the cat command
* sleep [detail](./sleep/README.md)

## progress
progress = 33 / 92 = 35%
progress = 34 / 92 = 36.7%
5 changes: 5 additions & 0 deletions coreutils/coreutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/guonaihong/coreutils/cut"
"github.com/guonaihong/coreutils/dirname"
"github.com/guonaihong/coreutils/echo"
"github.com/guonaihong/coreutils/env"
"github.com/guonaihong/coreutils/head"
"github.com/guonaihong/coreutils/link"
"github.com/guonaihong/coreutils/md5sum"
Expand Down Expand Up @@ -90,6 +91,10 @@ func main() {
echo.Main(os.Args[1:])
})

parent.SubCommand("env", "Use the env subcommand", func() {
env.Main(os.Args[1:])
})

parent.SubCommand("head", "Use the head subcommand", func() {
head.Main(os.Args[1:])
})
Expand Down
60 changes: 60 additions & 0 deletions env/env.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package env

import (
"fmt"
"github.com/guonaihong/flag"
"os"
"os/exec"
"strings"
)

type Env struct {
IgnoreEnvironment bool `opt:"i, ignore-environment" usage:"start with an empty environment"`
Unset string `opt:"u, unset" usage:"remove variable from the environment"`
//Chdir string `opt:"C, chdir" usage:"change working directory to DIR"`
Null bool `opt:"0, null" usage:"end each output line with NUL, not newline"`
}

func Main(argv []string) {
var env Env
delimiter := byte('\n')

command := flag.NewFlagSet(argv[0], flag.ExitOnError)
command.ParseStruct(argv[1:], &env)
args := command.Args()

if env.IgnoreEnvironment {
os.Clearenv()
}

if env.Null {
delimiter = byte(0)
}

for k, v := range args {
if strings.IndexByte(v, '=') > 0 {
kv := strings.SplitN(v, "=", 2)
if err := os.Setenv(kv[0], kv[1]); err != nil {
fmt.Printf("%s\n", err)
}
continue
}

cmd := exec.Command(args[k], args[k+1:]...)
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
fmt.Printf("%s\n", err)
os.Exit(1)
}

os.Exit(0)
}

allArgs := os.Environ()
for _, v := range allArgs {
fmt.Fprintf(os.Stdout, "%s%c", v, delimiter)
}
}

0 comments on commit 0372a04

Please sign in to comment.