Browse Source

halfway done of get

pull/103/head
Unknown 11 years ago
parent
commit
4ea34afd3f
  1. 2
      .gopmfile
  2. 168
      cmd/get.go
  3. 190
      gopm.go
  4. 39
      log/log_nonwindows.go

2
.gopmfile

@ -1,2 +1,4 @@
[target]
path = github.com/gpmgo/gopm
[deps]

168
cmd/get.go

@ -21,7 +21,10 @@ import (
"strings"
"github.com/Unknwon/com"
"github.com/codegangsta/cli"
"github.com/gpmgo/gopm/doc"
"github.com/gpmgo/gopm/log"
)
var (
@ -31,39 +34,83 @@ var (
failConut int
)
var CmdGet = &Command{
UsageLine: "get [flags] <package(s)>",
Short: "download and install packages and dependencies",
Long: `
Get downloads and installs the packages named by the import paths,
along with their dependencies.
This command works even you haven't installed any version control tool
such as git, hg, etc.
The install flags are:
var CmdGet = cli.Command{
Name: "get",
Usage: "fetch remote package(s) and dependencies to local repository",
Description: `Command get fetches a package, and any pakcages that it depents on.
If the package has a gopmfile, the fetch process will be driven by that.
-d
download without installing package(s).
-u
force to update pakcage(s).
-e
download dependencies for example(s).
gopm get
gopm get <import path>@[<tag|commit|branch>:<value>]
gopm get <package name>@[<tag|commit|branch>:<value>]
The list flags accept a space-separated list of strings.
Can specify one or more: gopm get beego@tag:v0.9.0 github.com/beego/bee
For more about specifying packages, see 'go help packages'.
`,
If no argument is supplied, then gopmfile must be present`,
Action: runGet,
Flags: []cli.Flag{
cli.BoolFlag{"force", "force to update pakcage(s) and dependencies"},
cli.BoolFlag{"example", "download dependencies for example(s)"},
},
}
func init() {
downloadCache = make(map[string]bool)
CmdGet.Run = runGet
CmdGet.Flags = map[string]bool{
"-d": false,
"-u": false,
"-e": false,
}
func runGet(ctx *cli.Context) {
// Check number of arguments.
switch len(ctx.Args()) {
case 0:
getByGopmfile(ctx)
}
}
func getByGopmfile(ctx *cli.Context) {
if !com.IsFile(".gopmfile") {
log.Fatal("install", "No argument is supplied and no gopmfile exist")
}
hd, err := com.HomeDir()
if err != nil {
log.Error("install", "Fail to get current user")
log.Fatal("", err.Error())
}
installRepoPath = strings.Replace(reposDir, "~", hd, -1)
log.Log("Local repository path: %s", installRepoPath)
// TODO: 获取依赖包
log.Error("install", "command haven't done yet!")
}
func processGet() {
}
func runGet1(cmd *Command, args []string) {
nodes := []*doc.Node{}
// ver describles branch, tag or commit.
var t, ver string = doc.BRANCH, ""
var err error
if len(args) >= 2 {
t, ver, err = validPath(args[1])
if err != nil {
com.ColorLog("[ERROR] Fail to parse 'args'[ %s ]\n", err)
return
}
}
node := doc.NewNode(args[0], args[0], t, ver, true)
nodes = append(nodes, node)
// Download package(s).
downloadPackages(nodes)
com.ColorLog("[INFO] %d package(s) downloaded, %d failed.\n",
downloadCount, failConut)
}
// printGetPrompt prints prompt information to users to
@ -107,51 +154,6 @@ func checkFlags(flags map[string]bool, args []string, print func(string)) int {
return num
}
func runGet(cmd *Command, args []string) {
// Check flags.
num := checkFlags(cmd.Flags, args, printGetPrompt)
if num == -1 {
return
}
args = args[num:]
// Check length of arguments.
if len(args) < 1 {
com.ColorLog("[ERRO] Please list the package that you want to install.\n")
return
}
hd, err := com.HomeDir()
if err != nil {
com.ColorLog("[ERRO] Fail to get current user[ %s ]\n", err)
return
}
installRepoPath = strings.Replace(reposDir, "~", hd, -1)
com.ColorLog("[INFO] Packages will be installed into( %s )\n", installRepoPath)
nodes := []*doc.Node{}
// ver describles branch, tag or commit.
var t, ver string = doc.BRANCH, ""
if len(args) >= 2 {
t, ver, err = validPath(args[1])
if err != nil {
com.ColorLog("[ERROR] Fail to parse 'args'[ %s ]\n", err)
return
}
}
node := doc.NewNode(args[0], args[0], t, ver, true)
nodes = append(nodes, node)
// Download package(s).
downloadPackages(nodes)
com.ColorLog("[INFO] %d package(s) downloaded, %d failed.\n",
downloadCount, failConut)
}
// downloadPackages downloads packages with certain commit,
// if the commit is empty string, then it downloads all dependencies,
// otherwise, it only downloada package with specific commit only.
@ -160,18 +162,18 @@ func downloadPackages(nodes []*doc.Node) {
for _, n := range nodes {
// Check if it is a valid remote path.
if doc.IsValidRemotePath(n.ImportPath) {
if !CmdGet.Flags["-u"] {
// Check if package has been downloaded.
installPath := installRepoPath + "/" + doc.GetProjectPath(n.ImportPath)
if len(n.Value) > 0 {
installPath += "." + n.Value
}
if com.IsExist(installPath) {
com.ColorLog("[WARN] Skipped installed package( %s => %s:%s )\n",
n.ImportPath, n.Type, doc.CheckNodeValue(n.Value))
continue
}
}
// if !CmdGet.Flags["-u"] {
// // Check if package has been downloaded.
// installPath := installRepoPath + "/" + doc.GetProjectPath(n.ImportPath)
// if len(n.Value) > 0 {
// installPath += "." + n.Value
// }
// if com.IsExist(installPath) {
// com.ColorLog("[WARN] Skipped installed package( %s => %s:%s )\n",
// n.ImportPath, n.Type, doc.CheckNodeValue(n.Value))
// continue
// }
// }
if !downloadCache[n.ImportPath] {
// Download package.
@ -216,7 +218,7 @@ func downloadPackage(nod *doc.Node) (*doc.Node, []string) {
// Mark as donwloaded.
downloadCache[nod.ImportPath] = true
imports, err := doc.PureDownload(nod, installRepoPath, CmdGet.Flags)
imports, err := doc.PureDownload(nod, installRepoPath, nil) //CmdGet.Flags)
if err != nil {
com.ColorLog("[ERRO] Download falied( %s )[ %s ]\n", nod.ImportPath, err)

190
gopm.go

@ -16,17 +16,11 @@
package main
import (
"fmt"
"io"
"os"
"runtime"
"strings"
"sync"
"text/template"
"unicode"
"unicode/utf8"
//"github.com/Unknwon/com"
"github.com/codegangsta/cli"
"github.com/gpmgo/gopm/cmd"
)
@ -38,171 +32,33 @@ const go11tag = true
const APP_VER = "0.5.1.1108"
// Commands lists the available commands and help topics.
// The order here is the order in which they are printed by 'gopm help'.
var commands = []*cmd.Command{
cmd.CmdGet,
//cmd.CmdSearch,
//cmd.CmdServe,
cmd.CmdGen,
cmd.CmdRun,
cmd.CmdBuild,
cmd.CmdInstall,
/*
cmdClean,
cmdDoc,
cmdEnv,
cmdFix,
cmdFmt,
cmdList,
cmdTest,
cmdTool,
cmdVet,
helpGopath,
helpPackages,
helpRemote,
helpTestflag,
helpTestfunc,*/
}
// //cmd.CmdSearch,
// cmd.CmdGen,
// cmd.CmdRun,
// cmd.CmdBuild,
// cmd.CmdInstall,
// cmdClean,
// cmdDoc,
// cmdEnv,
// cmdFix,
// cmdList,
// cmdTest,
// cmdTool,
// cmdVet,
// }
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())
}
func main() {
// Check length of arguments.
args := os.Args[1:]
if len(args) < 1 {
usage()
return
}
// Show help documentation.
if args[0] == "help" {
help(args[1:])
return
}
// Check commands and run.
for _, comm := range commands {
if comm.Name() == args[0] && comm.Run != nil {
// if comm.Name() != "serve" {
// err := cmd.AutoRun()
// if err == nil {
// comm.Run(comm, args[1:])
// } else {
// com.ColorLog("[ERRO] %v\n", err)
// }
// } else {
comm.Run(comm, args[1:])
// }
exit()
return
}
}
fmt.Fprintf(os.Stderr, "gopm: unknown subcommand %q\nRun 'gopm help' for usage.\n", args[0])
setExitStatus(2)
exit()
}
var exitStatus = 0
var exitMu sync.Mutex
func setExitStatus(n int) {
exitMu.Lock()
if exitStatus < n {
exitStatus = n
}
exitMu.Unlock()
}
var usageTemplate = `
Usage: gopm <command> [args]
The commands are:
{{range .}}{{if .Runnable}}
{{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}}
Use "gopm help [command]" for more information about a command.
Additional help topics:
{{range .}}{{if not .Runnable}}
{{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}}
Use "gopm help [topic]" for more information about that topic.
` + `gopm@` + APP_VER + "\n"
var helpTemplate = `{{if .Runnable}}usage: gopm {{.UsageLine}}
{{end}}{{.Long | trim}}
`
// tmpl executes the given template text on data, writing the result to w.
func tmpl(w io.Writer, text string, data interface{}) {
t := template.New("top")
t.Funcs(template.FuncMap{"trim": strings.TrimSpace, "capitalize": capitalize})
template.Must(t.Parse(text))
if err := t.Execute(w, data); err != nil {
panic(err)
}
}
func capitalize(s string) string {
if s == "" {
return s
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToTitle(r)) + s[n:]
}
func printUsage(w io.Writer) {
tmpl(w, usageTemplate, commands)
}
func usage() {
printUsage(os.Stderr)
os.Exit(2)
}
// help implements the 'help' command.
func help(args []string) {
if len(args) == 0 {
printUsage(os.Stdout)
// not exit 2: succeeded at 'gopm help'.
return
}
if len(args) != 1 {
fmt.Fprintf(os.Stderr, "usage: gopm help command\n\nToo many arguments given.\n")
os.Exit(2) // failed at 'gopm help'
}
arg := args[0]
for _, cmd := range commands {
if cmd.Name() == arg {
tmpl(os.Stdout, helpTemplate, cmd)
// not exit 2: succeeded at 'gopm help cmd'.
return
}
}
fmt.Fprintf(os.Stderr, "Unknown help topic %#q. Run 'gopm help'.\n", arg)
os.Exit(2) // failed at 'gopm help cmd'
}
var atexitFuncs []func()
func atexit(f func()) {
atexitFuncs = append(atexitFuncs, f)
}
func exit() {
for _, f := range atexitFuncs {
f()
app := cli.NewApp()
app.Name = "gopm"
app.Usage = "Go Package Manager"
app.Version = APP_VER
app.Commands = []cli.Command{
cmd.CmdGet,
}
os.Exit(exitStatus)
app.Run(os.Args)
}

39
log/log_nonwindows.go

@ -0,0 +1,39 @@
// Copyright 2013 gopm authors.
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package log
import (
"fmt"
"os"
"github.com/aybabtme/color/brush"
)
func Error(hl, msg string) {
if len(hl) > 0 {
hl = brush.Red(hl).String()
}
fmt.Printf("gopm %s %s %s\n", brush.Red("ERR!"), hl, msg)
}
func Fatal(hl, msg string) {
Error(hl, msg)
os.Exit(2)
}
func Log(format string, args ...interface{}) {
fmt.Printf("gopm %s %s\n", brush.White("INFO"),
fmt.Sprintf(format, args...))
}
Loading…
Cancel
Save