Browse Source

Still working on get command

pull/103/head
Unknown 11 years ago
parent
commit
f69ced6334
  1. 6
      cmd/gen.go
  2. 176
      cmd/get.go
  3. 318
      cmd/gopath.go
  4. 6
      cmd/search.go
  5. 1
      doc/doc
  6. 115
      doc/gopmfile.go
  7. 101
      doc/utils.go
  8. 5
      doc/vcs.go
  9. 10
      doc/walker.go
  10. 23
      log/log_nonwindows.go
  11. 56
      log/log_windows.go

6
cmd/gen.go

@ -64,12 +64,6 @@ func getPkgs(path string, inludeSys bool) ([]string, error) {
// scan a directory and gen a gopm file // scan a directory and gen a gopm file
func runGen(cmd *Command, args []string) { func runGen(cmd *Command, args []string) {
// Check flags.
num := checkFlags(cmd.Flags, args, printGenPrompt)
if num == -1 {
return
}
args = args[num:]
var gopmFile string = ".gopmfile" var gopmFile string = ".gopmfile"
if len(args) > 0 { if len(args) > 0 {

176
cmd/get.go

@ -18,6 +18,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"os" "os"
"path/filepath"
"strings" "strings"
"github.com/Unknwon/com" "github.com/Unknwon/com"
@ -59,145 +60,149 @@ func init() {
} }
func runGet(ctx *cli.Context) { func runGet(ctx *cli.Context) {
hd, err := com.HomeDir()
if err != nil {
log.Error("get", "Fail to get current user")
log.Fatal("", err.Error())
}
installRepoPath = strings.Replace(reposDir, "~", hd, -1)
log.Log("Local repository path: %s", installRepoPath)
// Check number of arguments. // Check number of arguments.
switch len(ctx.Args()) { switch len(ctx.Args()) {
case 0: case 0:
getByGopmfile(ctx) getByGopmfile(ctx)
default:
getByPath(ctx)
} }
} }
func getByGopmfile(ctx *cli.Context) { func getByGopmfile(ctx *cli.Context) {
if !com.IsFile(".gopmfile") { if !com.IsFile(".gopmfile") {
log.Fatal("install", "No argument is supplied and no gopmfile exist") log.Fatal("get", "No argument is supplied and no gopmfile exist")
} }
hd, err := com.HomeDir() gf := doc.NewGopmfile(".")
absPath, err := filepath.Abs(".")
if err != nil { if err != nil {
log.Error("install", "Fail to get current user") log.Error("", "Fail to get absolute path of work directory")
log.Fatal("", err.Error()) log.Fatal("", err.Error())
} }
installRepoPath = strings.Replace(reposDir, "~", hd, -1) log.Log("Work directory: %s", absPath)
log.Log("Local repository path: %s", installRepoPath)
// TODO: 获取依赖包 // Get dependencies.
imports := doc.GetAllImports([]string{absPath},
gf.MustValue("target", "path"), ctx.Bool("example"))
log.Error("install", "command haven't done yet!") nodes := make([]*doc.Node, 0, len(imports))
} for _, p := range imports {
node := doc.NewNode(p, p, doc.BRANCH, "", true)
func processGet() { // Check if user specified the version.
if v, err := gf.GetValue("deps", p); err == nil {
} tp, ver, err := validPath(v)
if err != nil {
func runGet1(cmd *Command, args []string) { log.Error("", "Fail to parse version")
nodes := []*doc.Node{} log.Fatal("", err.Error())
// ver describles branch, tag or commit. }
var t, ver string = doc.BRANCH, "" node.Type = tp
node.Value = ver
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
} }
nodes = append(nodes, node)
} }
node := doc.NewNode(args[0], args[0], t, ver, true) downloadPackages(ctx, nodes)
nodes = append(nodes, node)
// Download package(s). log.Log("%d package(s) downloaded, %d failed",
downloadPackages(nodes)
com.ColorLog("[INFO] %d package(s) downloaded, %d failed.\n",
downloadCount, failConut) downloadCount, failConut)
} }
// printGetPrompt prints prompt information to users to func getByPath(ctx *cli.Context) {
// let them know what's going on. nodes := make([]*doc.Node, 0, len(ctx.Args()))
func printGetPrompt(flag string) { for _, info := range ctx.Args() {
switch flag { pkg := info
case "-d": node := doc.NewNode(pkg, pkg, doc.BRANCH, "", true)
com.ColorLog("[INFO] You enabled download without installing.\n")
case "-u": if i := strings.Index(info, "@"); i > -1 {
com.ColorLog("[INFO] You enabled force update.\n") pkg = info[:i]
case "-e": tp, ver, err := validPath(info[i+1:])
com.ColorLog("[INFO] You enabled download dependencies of example(s).\n") if err != nil {
} log.Error("", "Fail to parse version")
} log.Fatal("", err.Error())
}
// checkFlags checks if the flag exists with correct format. node = doc.NewNode(pkg, pkg, tp, ver, true)
func checkFlags(flags map[string]bool, args []string, print func(string)) int {
num := 0 // Number of valid flags, use to cut out.
for i, f := range args {
// Check flag prefix '-'.
if !strings.HasPrefix(f, "-") {
// Not a flag, finish check process.
break
} }
// Check if it a valid flag. // Cheeck package name.
if v, ok := flags[f]; ok { if !strings.Contains(pkg, "/") {
flags[f] = !v name, ok := doc.PackageNameList[pkg]
if !v { if !ok {
print(f) log.Error("", "Invalid package name: "+pkg)
} else { log.Fatal("", "No match in the package name list")
fmt.Println("DISABLE: " + f)
} }
} else { pkg = name
com.ColorLog("[ERRO] Unknown flag: %s.\n", f)
return -1
} }
num = i + 1
nodes = append(nodes, node)
} }
return num downloadPackages(ctx, nodes)
log.Log("%d package(s) downloaded, %d failed",
downloadCount, failConut)
} }
// downloadPackages downloads packages with certain commit, // downloadPackages downloads packages with certain commit,
// if the commit is empty string, then it downloads all dependencies, // if the commit is empty string, then it downloads all dependencies,
// otherwise, it only downloada package with specific commit only. // otherwise, it only downloada package with specific commit only.
func downloadPackages(nodes []*doc.Node) { func downloadPackages(ctx *cli.Context, nodes []*doc.Node) {
// Check all packages, they may be raw packages path. // Check all packages, they may be raw packages path.
for _, n := range nodes { for _, n := range nodes {
// Check if it is a valid remote path. // Check if it is a valid remote path.
if doc.IsValidRemotePath(n.ImportPath) { if doc.IsValidRemotePath(n.ImportPath) {
// if !CmdGet.Flags["-u"] { if !ctx.Bool("force") {
// // Check if package has been downloaded. // Check if package has been downloaded.
// installPath := installRepoPath + "/" + doc.GetProjectPath(n.ImportPath) installPath := installRepoPath + "/" + doc.GetProjectPath(n.ImportPath)
// if len(n.Value) > 0 { if len(n.Value) > 0 {
// installPath += "." + n.Value installPath += "." + n.Value
// } }
// if com.IsExist(installPath) { if com.IsExist(installPath) {
// com.ColorLog("[WARN] Skipped installed package( %s => %s:%s )\n", log.Trace("Skipped installed package: %s@%s:%s",
// n.ImportPath, n.Type, doc.CheckNodeValue(n.Value)) n.ImportPath, n.Type, doc.CheckNodeValue(n.Value))
// continue continue
// } }
// } }
if !downloadCache[n.ImportPath] { if !downloadCache[n.ImportPath] {
// Download package. // Download package.
nod, imports := downloadPackage(n) nod, imports := downloadPackage(n)
if len(imports) > 0 { if len(imports) > 0 {
// TODO: 检查是否有 gopmfile
// Need to download dependencies. // Need to download dependencies.
// Generate temporary nodes. // Generate temporary nodes.
nodes := make([]*doc.Node, len(imports)) nodes := make([]*doc.Node, len(imports))
for i := range nodes { for i := range nodes {
nodes[i] = doc.NewNode(imports[i], imports[i], doc.BRANCH, "", true) nodes[i] = doc.NewNode(imports[i], imports[i], doc.BRANCH, "", true)
} }
downloadPackages(nodes) downloadPackages(ctx, nodes)
} }
// Only save package information with specific commit. // Only save package information with specific commit.
if nod != nil { if nod != nil {
// Save record in local nodes. // Save record in local nodes.
com.ColorLog("[SUCC] Downloaded package( %s => %s:%s )\n", log.Success("SUCC", "GET", fmt.Sprintf("%s@%s:%s",
n.ImportPath, n.Type, doc.CheckNodeValue(n.Value)) n.ImportPath, n.Type, doc.CheckNodeValue(n.Value)))
downloadCount++ downloadCount++
// TODO: 保存包信息
//saveNode(nod) //saveNode(nod)
} }
} else { } else {
com.ColorLog("[WARN] Skipped downloaded package( %s => %s:%s )\n", log.Trace("Skipped downloaded package: %s@%s:%s",
n.ImportPath, n.Type, doc.CheckNodeValue(n.Value)) n.ImportPath, n.Type, doc.CheckNodeValue(n.Value))
} }
} else if n.ImportPath == "C" { } else if n.ImportPath == "C" {
@ -213,15 +218,16 @@ func downloadPackages(nodes []*doc.Node) {
// downloadPackage downloads package either use version control tools or not. // downloadPackage downloads package either use version control tools or not.
func downloadPackage(nod *doc.Node) (*doc.Node, []string) { func downloadPackage(nod *doc.Node) (*doc.Node, []string) {
com.ColorLog("[TRAC] Downloading package( %s => %s:%s )\n", log.Message("Downloading", fmt.Sprintf("package: %s@%s:%s",
nod.ImportPath, nod.Type, doc.CheckNodeValue(nod.Value)) nod.ImportPath, nod.Type, doc.CheckNodeValue(nod.Value)))
// Mark as donwloaded. // Mark as donwloaded.
downloadCache[nod.ImportPath] = true downloadCache[nod.ImportPath] = true
imports, err := doc.PureDownload(nod, installRepoPath, nil) //CmdGet.Flags) imports, err := doc.PureDownload(nod, installRepoPath, nil) //CmdGet.Flags)
if err != nil { if err != nil {
com.ColorLog("[ERRO] Download falied( %s )[ %s ]\n", nod.ImportPath, err) log.Error("Get", "Fail to download pakage: "+nod.ImportPath)
log.Fatal("", err.Error())
failConut++ failConut++
os.RemoveAll(installRepoPath + "/" + doc.GetProjectPath(nod.ImportPath) + "/") os.RemoveAll(installRepoPath + "/" + doc.GetProjectPath(nod.ImportPath) + "/")
return nil, nil return nil, nil
@ -231,12 +237,10 @@ func downloadPackage(nod *doc.Node) (*doc.Node, []string) {
// validPath checks if the information of the package is valid. // validPath checks if the information of the package is valid.
func validPath(info string) (string, string, error) { func validPath(info string) (string, string, error) {
infos := strings.Split(info, ":") infos := strings.SplitN(info, ":", 2)
l := len(infos) l := len(infos)
switch { switch {
case l > 2:
return "", "", errors.New("Invalid information of package")
case l == 1: case l == 1:
return doc.BRANCH, "", nil return doc.BRANCH, "", nil
case l == 2: case l == 2:
@ -246,6 +250,6 @@ func validPath(info string) (string, string, error) {
} }
return infos[0], infos[1], nil return infos[0], infos[1], nil
default: default:
return "", "", errors.New("Cannot match any case") return "", "", errors.New("Invalid version information")
} }
} }

318
cmd/gopath.go

@ -3,51 +3,51 @@ package cmd
import ( import (
"github.com/Unknwon/com" "github.com/Unknwon/com"
"github.com/gpmgo/gopm/doc" "github.com/gpmgo/gopm/doc"
"go/build" //"go/build"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"strings" //"strings"
) )
func getGopmPkgs(path string, inludeSys bool) (map[string]*doc.Pkg, error) { func getGopmPkgs(path string, inludeSys bool) (map[string]*doc.Pkg, error) {
abs, err := filepath.Abs(filepath.Join(path, doc.GopmFileName)) // abs, err := filepath.Abs(filepath.Join(path, doc.GopmFileName))
if err != nil { // if err != nil {
return nil, err // return nil, err
} // }
// load import path // // load import path
gf := doc.NewGopmfile() // gf := doc.NewGopmfile()
var builds *doc.Section // var builds *doc.Section
if com.IsExist(abs) { // if com.IsExist(abs) {
err := gf.Load(abs) // err := gf.Load(abs)
if err != nil { // if err != nil {
return nil, err // return nil, err
} // }
var ok bool // var ok bool
if builds, ok = gf.Sections["build"]; !ok { // if builds, ok = gf.Sections["build"]; !ok {
builds = nil // builds = nil
} // }
} // }
pkg, err := build.ImportDir(path, build.AllowBinary) // pkg, err := build.ImportDir(path, build.AllowBinary)
if err != nil { // if err != nil {
return map[string]*doc.Pkg{}, err // return map[string]*doc.Pkg{}, err
} // }
pkgs := make(map[string]*doc.Pkg) // pkgs := make(map[string]*doc.Pkg)
for _, name := range pkg.Imports { // for _, name := range pkg.Imports {
if inludeSys || !isStdPkg(name) { // if inludeSys || !isStdPkg(name) {
if builds != nil { // if builds != nil {
if dep, ok := builds.Deps[name]; ok { // if dep, ok := builds.Deps[name]; ok {
pkgs[name] = dep.Pkg // pkgs[name] = dep.Pkg
continue // continue
} // }
} // }
pkgs[name] = doc.NewDefaultPkg(name) // pkgs[name] = doc.NewDefaultPkg(name)
} // }
} // }
return pkgs, nil return nil, nil //pkgs, nil
} }
func pkgInCache(name string, cachePkgs map[string]*doc.Pkg) bool { func pkgInCache(name string, cachePkgs map[string]*doc.Pkg) bool {
@ -63,41 +63,41 @@ func autoLink(oldPath, newPath string) error {
} }
func getChildPkgs(cpath string, ppkg *doc.Pkg, cachePkgs map[string]*doc.Pkg) error { func getChildPkgs(cpath string, ppkg *doc.Pkg, cachePkgs map[string]*doc.Pkg) error {
pkgs, err := getGopmPkgs(cpath, false) // pkgs, err := getGopmPkgs(cpath, false)
if err != nil { // if err != nil {
return err // return err
} // }
for name, pkg := range pkgs { // for name, pkg := range pkgs {
if !pkgInCache(name, cachePkgs) { // if !pkgInCache(name, cachePkgs) {
var newPath string // var newPath string
if !build.IsLocalImport(name) { // if !build.IsLocalImport(name) {
newPath = filepath.Join(installRepoPath, pkg.ImportPath) // newPath = filepath.Join(installRepoPath, pkg.ImportPath)
if pkgName != "" && strings.HasPrefix(pkg.ImportPath, pkgName) { // if pkgName != "" && strings.HasPrefix(pkg.ImportPath, pkgName) {
newPath = filepath.Join(curPath, pkg.ImportPath[len(pkgName)+1:]) // newPath = filepath.Join(curPath, pkg.ImportPath[len(pkgName)+1:])
} else { // } else {
if !com.IsExist(newPath) { // if !com.IsExist(newPath) {
var t, ver string = doc.BRANCH, "" // var t, ver string = doc.BRANCH, ""
node := doc.NewNode(pkg.ImportPath, pkg.ImportPath, t, ver, true) // node := doc.NewNode(pkg.ImportPath, pkg.ImportPath, t, ver, true)
nodes := []*doc.Node{node} // nodes := []*doc.Node{node}
downloadPackages(nodes) // downloadPackages(nodes)
// should handler download failed // // should handler download failed
} // }
} // }
} else { // } else {
newPath, err = filepath.Abs(name) // newPath, err = filepath.Abs(name)
if err != nil { // if err != nil {
return err // return err
} // }
} // }
err = getChildPkgs(newPath, pkg, cachePkgs) // err = getChildPkgs(newPath, pkg, cachePkgs)
if err != nil { // if err != nil {
return err // return err
} // }
} // }
} // }
if ppkg != nil && !build.IsLocalImport(ppkg.ImportPath) { // if ppkg != nil && !build.IsLocalImport(ppkg.ImportPath) {
cachePkgs[ppkg.ImportPath] = ppkg // cachePkgs[ppkg.ImportPath] = ppkg
} // }
return nil return nil
} }
@ -150,89 +150,89 @@ func execCmd(gopath, curPath string, args ...string) error {
} }
func genNewGoPath() { func genNewGoPath() {
var err error // var err error
curPath, err = os.Getwd() // curPath, err = os.Getwd()
if err != nil { // if err != nil {
com.ColorLog("[ERRO] %v\n", err) // com.ColorLog("[ERRO] %v\n", err)
return // return
} // }
hd, err := com.HomeDir() // hd, err := com.HomeDir()
if err != nil { // if err != nil {
com.ColorLog("[ERRO] Fail to get current user[ %s ]\n", err) // com.ColorLog("[ERRO] Fail to get current user[ %s ]\n", err)
return // return
} // }
gf := doc.NewGopmfile() // gf := doc.NewGopmfile()
gpmPath := filepath.Join(curPath, doc.GopmFileName) // gpmPath := filepath.Join(curPath, doc.GopmFileName)
if com.IsExist(gpmPath) { // if com.IsExist(gpmPath) {
com.ColorLog("[INFO] loading .gopmfile ...\n") // com.ColorLog("[INFO] loading .gopmfile ...\n")
err := gf.Load(gpmPath) // err := gf.Load(gpmPath)
if err != nil { // if err != nil {
com.ColorLog("[ERRO] load .gopmfile failed: %v\n", err) // com.ColorLog("[ERRO] load .gopmfile failed: %v\n", err)
return // return
} // }
} // }
installRepoPath = strings.Replace(reposDir, "~", hd, -1) // installRepoPath = strings.Replace(reposDir, "~", hd, -1)
cachePkgs := make(map[string]*doc.Pkg) // cachePkgs := make(map[string]*doc.Pkg)
if target, ok := gf.Sections["target"]; ok { // if target, ok := gf.Sections["target"]; ok {
pkgName = target.Props["path"] // pkgName = target.Props["path"]
com.ColorLog("[INFO] target name is %v\n", pkgName) // com.ColorLog("[INFO] target name is %v\n", pkgName)
} // }
if pkgName == "" { // if pkgName == "" {
_, pkgName = filepath.Split(curPath) // _, pkgName = filepath.Split(curPath)
} // }
err = getChildPkgs(curPath, nil, cachePkgs) // err = getChildPkgs(curPath, nil, cachePkgs)
if err != nil { // if err != nil {
com.ColorLog("[ERRO] %v\n", err) // com.ColorLog("[ERRO] %v\n", err)
return // return
} // }
newGoPath = filepath.Join(curPath, "vendor") // newGoPath = filepath.Join(curPath, "vendor")
newGoPathSrc := filepath.Join(newGoPath, "src") // newGoPathSrc := filepath.Join(newGoPath, "src")
os.RemoveAll(newGoPathSrc) // os.RemoveAll(newGoPathSrc)
os.MkdirAll(newGoPathSrc, os.ModePerm) // os.MkdirAll(newGoPathSrc, os.ModePerm)
for name, _ := range cachePkgs { // for name, _ := range cachePkgs {
oldPath := filepath.Join(installRepoPath, name) // oldPath := filepath.Join(installRepoPath, name)
newPath := filepath.Join(newGoPathSrc, name) // newPath := filepath.Join(newGoPathSrc, name)
paths := strings.Split(name, "/") // paths := strings.Split(name, "/")
var isExistP bool // var isExistP bool
var isCurChild bool // var isCurChild bool
for i := 0; i < len(paths)-1; i++ { // for i := 0; i < len(paths)-1; i++ {
pName := strings.Join(paths[:len(paths)-1-i], "/") // pName := strings.Join(paths[:len(paths)-1-i], "/")
if _, ok := cachePkgs[pName]; ok { // if _, ok := cachePkgs[pName]; ok {
isExistP = true // isExistP = true
break // break
} // }
if pkgName == pName { // if pkgName == pName {
isCurChild = true // isCurChild = true
break // break
} // }
} // }
if isCurChild { // if isCurChild {
continue // continue
} // }
if !isExistP { // if !isExistP {
com.ColorLog("[INFO] linked %v\n", name) // com.ColorLog("[INFO] linked %v\n", name)
err = autoLink(oldPath, newPath) // err = autoLink(oldPath, newPath)
if err != nil { // if err != nil {
com.ColorLog("[ERRO] make link error %v\n", err) // com.ColorLog("[ERRO] make link error %v\n", err)
return // return
} // }
} // }
} // }
newCurPath = filepath.Join(newGoPathSrc, pkgName) // newCurPath = filepath.Join(newGoPathSrc, pkgName)
com.ColorLog("[INFO] linked %v\n", pkgName) // com.ColorLog("[INFO] linked %v\n", pkgName)
err = autoLink(curPath, newCurPath) // err = autoLink(curPath, newCurPath)
if err != nil { // if err != nil {
com.ColorLog("[ERRO] make link error %v\n", err) // com.ColorLog("[ERRO] make link error %v\n", err)
return // return
} // }
} }

6
cmd/search.go

@ -52,12 +52,6 @@ func printSearchPrompt(flag string) {
// search packages // search packages
func runSearch(cmd *Command, args []string) { func runSearch(cmd *Command, args []string) {
// Check flags.
num := checkFlags(cmd.Flags, args, printSearchPrompt)
if num == -1 {
return
}
args = args[num:]
// Check length of arguments. // Check length of arguments.
if len(args) < 1 { if len(args) < 1 {

1
doc/doc

@ -1 +0,0 @@
/Users/lunny/go/src/github.com/gpmgo/gopm/doc

115
doc/gopmfile.go

@ -1,105 +1,40 @@
// 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 doc package doc
import ( import (
"bufio" "github.com/Unknwon/goconfig"
"os"
"strings"
)
const (
Greater = ">"
GreaterOrEq = ">="
Equeal = "="
Lesser = "<"
LesserOrEq = "<="
)
var ( "github.com/gpmgo/gopm/log"
Ops = []string{GreaterOrEq, LesserOrEq, Greater, Equeal, Lesser}
) )
const ( const (
GopmFileName = ".gopmfile" GopmFileName = ".gopmfile"
) )
type Depend struct { func NewGopmfile(dirPath string) *goconfig.ConfigFile {
Pkg *Pkg gf, err := goconfig.LoadConfigFile(dirPath + "/" + GopmFileName)
Op string
Ver string
}
type Section struct {
Name string
Deps map[string]*Depend
Props map[string]string
}
func NewSection() *Section {
return &Section{Deps: make(map[string]*Depend),
Props: make(map[string]string),
}
}
type Gopmfile struct {
Sections map[string]*Section
}
func NewGopmfile() *Gopmfile {
return &Gopmfile{Sections: make(map[string]*Section)}
}
func (this *Gopmfile) Load(path string) error {
f, err := os.Open(path)
if err != nil { if err != nil {
return err log.Error("", "Fail to load gopmfile")
log.Fatal("", err.Error())
} }
return gf
scanner := bufio.NewScanner(f)
var sec *Section
for scanner.Scan() {
text := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(text, "[") && strings.HasSuffix(text, "]") {
sec = NewSection()
sec.Name = text[1 : len(text)-1]
this.Sections[sec.Name] = sec
} else {
if sec == nil {
continue
}
if sec.Name == "target" {
ss := strings.Split(text, "=")
if len(ss) == 1 {
sec.Props[strings.TrimSpace(ss[0])] = strings.TrimSpace(ss[0])
} else if len(ss) == 2 {
sec.Props[strings.TrimSpace(ss[0])] = strings.TrimSpace(ss[1])
}
} else {
var dep *Depend
for _, op := range Ops {
if strings.Contains(text, op) {
ss := strings.Split(text, op)
pkver := strings.Split(ss[1], ":")
var tp, value string
tp = pkver[0]
if len(pkver) == 2 {
value = pkver[1]
}
dep = &Depend{NewPkg(ss[0], tp, value), ss[1], value}
break
}
}
if dep == nil {
dep = &Depend{NewDefaultPkg(text), Equeal, ""}
}
sec.Deps[dep.Pkg.ImportPath] = dep
}
}
}
return nil
} }
func (this *Gopmfile) Save(path string) error { var PackageNameList map[string]string
return nil
func init() {
PackageNameList = make(map[string]string)
} }

101
doc/utils.go

@ -21,33 +21,96 @@ import (
"strings" "strings"
"github.com/Unknwon/com" "github.com/Unknwon/com"
)
// GetGOPATH returns best matched GOPATH. "github.com/gpmgo/gopm/log"
func GetBestMatchGOPATH(appPath string) string { )
paths := com.GetGOPATHs()
for _, p := range paths {
if strings.HasPrefix(p, appPath) {
return strings.Replace(p, "\\", "/", -1)
}
}
return paths[0]
}
// GetDirsInfo returns os.FileInfo of all sub-directories in root path. // GetDirsInfo returns os.FileInfo of all sub-directories in root path.
func GetDirsInfo(rootPath string) ([]os.FileInfo, error) { func GetDirsInfo(rootPath string) []os.FileInfo {
rootDir, err := os.Open(rootPath) rootDir, err := os.Open(rootPath)
if err != nil { if err != nil {
return nil, err log.Error("", "Fail to open directory")
log.Fatal("", err.Error())
} }
defer rootDir.Close() defer rootDir.Close()
dirs, err := rootDir.Readdir(0) dirs, err := rootDir.Readdir(0)
if err != nil { if err != nil {
return nil, err log.Error("", "Fail to read directory")
log.Fatal("", err.Error())
} }
return dirs, err return dirs
}
// GetImports returns package denpendencies.
func GetImports(absPath, importPath string, example bool) (imports []string) {
fis := GetDirsInfo(absPath)
absPath += "/"
dirs := make([]string, 0)
files := make([]*source, 0, 10)
for _, fi := range fis {
if fi.IsDir() {
dirs = append(dirs, absPath+fi.Name())
continue
}
if strings.HasSuffix(fi.Name(), ".go") {
data, err := com.ReadFile(absPath + fi.Name())
if err != nil {
log.Error("", "Fail to read file")
log.Fatal("", err.Error())
}
files = append(files, &source{
name: fi.Name(),
data: data,
})
}
}
var err error
if len(files) > 0 {
w := &walker{ImportPath: importPath}
imports, err = w.build(files, nil)
if err != nil {
log.Error("", "Fail to get imports")
log.Fatal("", err.Error())
}
}
if len(dirs) > 0 {
imports = append(imports, GetAllImports(dirs, importPath, example)...)
}
return imports
}
func isVcsPath(dirPath string) bool {
return strings.Contains(dirPath, "/.git") ||
strings.Contains(dirPath, "/.hg") ||
strings.Contains(dirPath, "/.svn")
}
func GetAllImports(dirs []string, importPath string, example bool) (imports []string) {
for _, d := range dirs {
if !isVcsPath(d) &&
!(!example && strings.Contains(d, "example")) {
imports = append(imports, GetImports(d, importPath, example)...)
}
}
return imports
}
// GetGOPATH returns best matched GOPATH.
func GetBestMatchGOPATH(appPath string) string {
paths := com.GetGOPATHs()
for _, p := range paths {
if strings.HasPrefix(p, appPath) {
return strings.Replace(p, "\\", "/", -1)
}
}
return paths[0]
} }
// CheckIsExistWithVCS returns false if directory only has VCS folder, // CheckIsExistWithVCS returns false if directory only has VCS folder,
@ -59,11 +122,7 @@ func CheckIsExistWithVCS(path string) bool {
} }
// Check if only has VCS folder. // Check if only has VCS folder.
dirs, err := GetDirsInfo(path) dirs := GetDirsInfo(path)
if err != nil {
com.ColorLog("[ERRO] CheckIsExistWithVCS -> [ %s ]\n", err)
return false
}
if len(dirs) > 1 { if len(dirs) > 1 {
return true return true
@ -478,7 +537,6 @@ var standardPath = map[string]bool{
"cmd/cgo": true, "cmd/cgo": true,
"cmd/fix": true, "cmd/fix": true,
"cmd/go": true, "cmd/go": true,
"cmd/godoc": true,
"cmd/gofmt": true, "cmd/gofmt": true,
"cmd/vet": true, "cmd/vet": true,
"cmd/yacc": true, "cmd/yacc": true,
@ -594,6 +652,7 @@ var standardPath = map[string]bool{
"runtime/cgo": true, "runtime/cgo": true,
"runtime/debug": true, "runtime/debug": true,
"runtime/pprof": true, "runtime/pprof": true,
"runtime/race": true,
"sort": true, "sort": true,
"strconv": true, "strconv": true,
"strings": true, "strings": true,

5
doc/vcs.go

@ -243,10 +243,7 @@ metaScan:
} }
func getImports(rootPath string, match map[string]string, cmdFlags map[string]bool, nod *Node) (imports []string) { func getImports(rootPath string, match map[string]string, cmdFlags map[string]bool, nod *Node) (imports []string) {
dirs, err := GetDirsInfo(rootPath) dirs := GetDirsInfo(rootPath)
if err != nil {
return nil
}
for _, d := range dirs { for _, d := range dirs {
if d.IsDir() && !(!cmdFlags["-e"] && strings.Contains(d.Name(), "example")) { if d.IsDir() && !(!cmdFlags["-e"] && strings.Contains(d.Name(), "example")) {

10
doc/walker.go

@ -153,10 +153,14 @@ func (w *walker) build(srcs []*source, nod *Node) ([]string, error) {
} }
pdoc := doc.New(apkg, w.ImportPath, mode) pdoc := doc.New(apkg, w.ImportPath, mode)
nod.Synopsis = Synopsis(pdoc.Doc)
if i := strings.Index(nod.Synopsis, "\n"); i > -1 { if nod != nil {
nod.Synopsis = nod.Synopsis[:i] nod.Synopsis = Synopsis(pdoc.Doc)
if i := strings.Index(nod.Synopsis, "\n"); i > -1 {
nod.Synopsis = nod.Synopsis[:i]
}
} }
return imports, err return imports, err
} }

23
log/log_nonwindows.go

@ -23,9 +23,9 @@ import (
func Error(hl, msg string) { func Error(hl, msg string) {
if len(hl) > 0 { if len(hl) > 0 {
hl = brush.Red(hl).String() hl = " " + brush.Red(hl).String()
} }
fmt.Printf("gopm %s %s %s\n", brush.Red("ERR!"), hl, msg) fmt.Printf("gopm %s%s %s\n", brush.Red("ERR!"), hl, msg)
} }
func Fatal(hl, msg string) { func Fatal(hl, msg string) {
@ -37,3 +37,22 @@ func Log(format string, args ...interface{}) {
fmt.Printf("gopm %s %s\n", brush.White("INFO"), fmt.Printf("gopm %s %s\n", brush.White("INFO"),
fmt.Sprintf(format, args...)) fmt.Sprintf(format, args...))
} }
func Trace(format string, args ...interface{}) {
fmt.Printf("gopm %s %s\n", brush.Blue("TRAC"),
fmt.Sprintf(format, args...))
}
func Success(title, hl, msg string) {
if len(hl) > 0 {
hl = " " + brush.Green(hl).String()
}
fmt.Printf("gopm %s%s %s\n", brush.Green(title), hl, msg)
}
func Message(hl, msg string) {
if len(hl) > 0 {
hl = " " + brush.Yellow(hl).String()
}
fmt.Printf("gopm %s%s %s\n", brush.Yellow("MSG!"), hl, msg)
}

56
log/log_windows.go

@ -0,0 +1,56 @@
// 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"
)
func Error(hl, msg string) {
if len(hl) > 0 {
hl = " " + hl
}
fmt.Printf("gopm ERR!%s %s\n", hl, msg)
}
func Fatal(hl, msg string) {
Error(hl, msg)
os.Exit(2)
}
func Log(format string, args ...interface{}) {
fmt.Printf("gopm INFO %s\n",
fmt.Sprintf(format, args...))
}
func Trace(format string, args ...interface{}) {
fmt.Printf("gopm TRAC %s\n",
fmt.Sprintf(format, args...))
}
func Success(title, hl, msg string) {
if len(hl) > 0 {
hl = " " + hl
}
fmt.Printf("gopm %s%s %s\n", title, hl, msg)
}
func Message(hl, msg string) {
if len(hl) > 0 {
hl = " " + hl
}
fmt.Printf("gopm MSG!%s %s\n", hl, msg)
}
Loading…
Cancel
Save