Browse Source

Lintify code with confidence=1

Guillaume J. Charmes 11 năm trước cách đây
mục cha
commit
5e941f1ca0
11 tập tin đã thay đổi với 199 bổ sung208 xóa
  1. 10 18
      api.go
  2. 123 125
      api_params.go
  3. 5 4
      archive/archive.go
  4. 2 3
      auth/auth.go
  5. 3 4
      commands.go
  6. 3 4
      graph.go
  7. 25 24
      image.go
  8. 1 1
      runtime.go
  9. 10 8
      server.go
  10. 11 11
      utils/http.go
  11. 6 6
      utils/utils.go

+ 10 - 18
api.go

@@ -149,13 +149,12 @@ func postContainersKill(srv *Server, version float64, w http.ResponseWriter, r *
 
 	signal := 0
 	if r != nil {
-		s := r.Form.Get("signal")
-		if s != "" {
-			if s, err := strconv.Atoi(s); err != nil {
+		if s := r.Form.Get("signal"); s != "" {
+			s, err := strconv.Atoi(s)
+			if err != nil {
 				return err
-			} else {
-				signal = s
 			}
+			signal = s
 		}
 	}
 	if err := srv.ContainerKill(name, signal); err != nil {
@@ -201,9 +200,8 @@ func getImagesJSON(srv *Server, version float64, w http.ResponseWriter, r *http.
 		}
 
 		return writeJSON(w, http.StatusOK, outs2)
-	} else {
-		return writeJSON(w, http.StatusOK, outs)
 	}
+	return writeJSON(w, http.StatusOK, outs)
 }
 
 func getImagesViz(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
@@ -316,13 +314,10 @@ func getContainersTop(srv *Server, version float64, w http.ResponseWriter, r *ht
 	if err := parseForm(r); err != nil {
 		return err
 	}
-	name := vars["name"]
-	ps_args := r.Form.Get("ps_args")
-	procsStr, err := srv.ContainerTop(name, ps_args)
+	procsStr, err := srv.ContainerTop(vars["name"], r.Form.Get("ps_args"))
 	if err != nil {
 		return err
 	}
-
 	return writeJSON(w, http.StatusOK, procsStr)
 }
 
@@ -350,13 +345,12 @@ func getContainersJSON(srv *Server, version float64, w http.ResponseWriter, r *h
 	if version < 1.5 {
 		outs2 := []APIContainersOld{}
 		for _, ctnr := range outs {
-			outs2 = append(outs2, ctnr.ToLegacy())
+			outs2 = append(outs2, *ctnr.ToLegacy())
 		}
 
 		return writeJSON(w, http.StatusOK, outs2)
-	} else {
-		return writeJSON(w, http.StatusOK, outs)
 	}
+	return writeJSON(w, http.StatusOK, outs)
 }
 
 func postImagesTag(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
@@ -640,12 +634,10 @@ func deleteImages(srv *Server, version float64, w http.ResponseWriter, r *http.R
 	if imgs != nil {
 		if len(imgs) != 0 {
 			return writeJSON(w, http.StatusOK, imgs)
-		} else {
-			return fmt.Errorf("Conflict, %s wasn't deleted", name)
 		}
-	} else {
-		w.WriteHeader(http.StatusNoContent)
+		return fmt.Errorf("Conflict, %s wasn't deleted", name)
 	}
+	w.WriteHeader(http.StatusNoContent)
 	return nil
 }
 

+ 123 - 125
api_params.go

@@ -2,149 +2,147 @@ package docker
 
 import "strings"
 
-type APIHistory struct {
-	ID        string   `json:"Id"`
-	Tags      []string `json:",omitempty"`
-	Created   int64
-	CreatedBy string `json:",omitempty"`
-	Size      int64
-}
-
-type APIImages struct {
-	ID          string   `json:"Id"`
-	RepoTags    []string `json:",omitempty"`
-	Created     int64
-	Size        int64
-	VirtualSize int64
-	ParentId    string `json:",omitempty"`
-}
-
-type APIImagesOld struct {
-	Repository  string `json:",omitempty"`
-	Tag         string `json:",omitempty"`
-	ID          string `json:"Id"`
-	Created     int64
-	Size        int64
-	VirtualSize int64
-}
-
-func (self *APIImages) ToLegacy() []APIImagesOld {
-
-	outs := []APIImagesOld{}
-	for _, repotag := range self.RepoTags {
+type (
+	APIHistory struct {
+		ID        string   `json:"Id"`
+		Tags      []string `json:",omitempty"`
+		Created   int64
+		CreatedBy string `json:",omitempty"`
+		Size      int64
+	}
 
-		components := strings.SplitN(repotag, ":", 2)
+	APIImages struct {
+		ID          string   `json:"Id"`
+		RepoTags    []string `json:",omitempty"`
+		Created     int64
+		Size        int64
+		VirtualSize int64
+		ParentId    string `json:",omitempty"`
+	}
 
-		outs = append(outs, APIImagesOld{
-			ID:          self.ID,
-			Repository:  components[0],
-			Tag:         components[1],
-			Created:     self.Created,
-			Size:        self.Size,
-			VirtualSize: self.VirtualSize,
-		})
+	APIImagesOld struct {
+		Repository  string `json:",omitempty"`
+		Tag         string `json:",omitempty"`
+		ID          string `json:"Id"`
+		Created     int64
+		Size        int64
+		VirtualSize int64
 	}
 
-	return outs
-}
+	APIInfo struct {
+		Debug              bool
+		Containers         int
+		Images             int
+		NFd                int    `json:",omitempty"`
+		NGoroutines        int    `json:",omitempty"`
+		MemoryLimit        bool   `json:",omitempty"`
+		SwapLimit          bool   `json:",omitempty"`
+		IPv4Forwarding     bool   `json:",omitempty"`
+		LXCVersion         string `json:",omitempty"`
+		NEventsListener    int    `json:",omitempty"`
+		KernelVersion      string `json:",omitempty"`
+		IndexServerAddress string `json:",omitempty"`
+	}
 
-type APIInfo struct {
-	Debug              bool
-	Containers         int
-	Images             int
-	NFd                int    `json:",omitempty"`
-	NGoroutines        int    `json:",omitempty"`
-	MemoryLimit        bool   `json:",omitempty"`
-	SwapLimit          bool   `json:",omitempty"`
-	IPv4Forwarding     bool   `json:",omitempty"`
-	LXCVersion         string `json:",omitempty"`
-	NEventsListener    int    `json:",omitempty"`
-	KernelVersion      string `json:",omitempty"`
-	IndexServerAddress string `json:",omitempty"`
-}
+	APITop struct {
+		Titles    []string
+		Processes [][]string
+	}
 
-type APITop struct {
-	Titles    []string
-	Processes [][]string
-}
+	APIRmi struct {
+		Deleted  string `json:",omitempty"`
+		Untagged string `json:",omitempty"`
+	}
 
-type APIRmi struct {
-	Deleted  string `json:",omitempty"`
-	Untagged string `json:",omitempty"`
-}
+	APIContainers struct {
+		ID         string `json:"Id"`
+		Image      string
+		Command    string
+		Created    int64
+		Status     string
+		Ports      []APIPort
+		SizeRw     int64
+		SizeRootFs int64
+		Names      []string
+	}
 
-type APIContainers struct {
-	ID         string `json:"Id"`
-	Image      string
-	Command    string
-	Created    int64
-	Status     string
-	Ports      []APIPort
-	SizeRw     int64
-	SizeRootFs int64
-	Names      []string
-}
+	APIContainersOld struct {
+		ID         string `json:"Id"`
+		Image      string
+		Command    string
+		Created    int64
+		Status     string
+		Ports      string
+		SizeRw     int64
+		SizeRootFs int64
+	}
 
-func (self *APIContainers) ToLegacy() APIContainersOld {
-	return APIContainersOld{
-		ID:         self.ID,
-		Image:      self.Image,
-		Command:    self.Command,
-		Created:    self.Created,
-		Status:     self.Status,
-		Ports:      displayablePorts(self.Ports),
-		SizeRw:     self.SizeRw,
-		SizeRootFs: self.SizeRootFs,
+	APIID struct {
+		ID string `json:"Id"`
 	}
-}
 
-type APIContainersOld struct {
-	ID         string `json:"Id"`
-	Image      string
-	Command    string
-	Created    int64
-	Status     string
-	Ports      string
-	SizeRw     int64
-	SizeRootFs int64
-}
+	APIRun struct {
+		ID       string   `json:"Id"`
+		Warnings []string `json:",omitempty"`
+	}
 
-type APIID struct {
-	ID string `json:"Id"`
-}
+	APIPort struct {
+		PrivatePort int64
+		PublicPort  int64
+		Type        string
+		IP          string
+	}
 
-type APIRun struct {
-	ID       string   `json:"Id"`
-	Warnings []string `json:",omitempty"`
-}
+	APIVersion struct {
+		Version   string
+		GitCommit string `json:",omitempty"`
+		GoVersion string `json:",omitempty"`
+	}
 
-type APIPort struct {
-	PrivatePort int64
-	PublicPort  int64
-	Type        string
-	IP          string
-}
+	APIWait struct {
+		StatusCode int
+	}
 
-type APIVersion struct {
-	Version   string
-	GitCommit string `json:",omitempty"`
-	GoVersion string `json:",omitempty"`
-}
+	APIAuth struct {
+		Status string
+	}
 
-type APIWait struct {
-	StatusCode int
-}
+	APIImageConfig struct {
+		ID string `json:"Id"`
+		*Config
+	}
 
-type APIAuth struct {
-	Status string
-}
+	APICopy struct {
+		Resource string
+		HostPath string
+	}
+)
 
-type APIImageConfig struct {
-	ID string `json:"Id"`
-	*Config
+func (api APIImages) ToLegacy() []APIImagesOld {
+	outs := []APIImagesOld{}
+	for _, repotag := range api.RepoTags {
+		components := strings.SplitN(repotag, ":", 2)
+		outs = append(outs, APIImagesOld{
+			ID:          api.ID,
+			Repository:  components[0],
+			Tag:         components[1],
+			Created:     api.Created,
+			Size:        api.Size,
+			VirtualSize: api.VirtualSize,
+		})
+	}
+	return outs
 }
 
-type APICopy struct {
-	Resource string
-	HostPath string
+func (api APIContainers) ToLegacy() *APIContainersOld {
+	return &APIContainersOld{
+		ID:         api.ID,
+		Image:      api.Image,
+		Command:    api.Command,
+		Created:    api.Created,
+		Status:     api.Status,
+		Ports:      displayablePorts(api.Ports),
+		SizeRw:     api.SizeRw,
+		SizeRootFs: api.SizeRootFs,
+	}
 }

+ 5 - 4
archive/archive.go

@@ -109,16 +109,17 @@ func Untar(archive io.Reader, path string) error {
 	buf := make([]byte, 10)
 	totalN := 0
 	for totalN < 10 {
-		if n, err := archive.Read(buf[totalN:]); err != nil {
+		n, err := archive.Read(buf[totalN:])
+		if err != nil {
 			if err == io.EOF {
 				return fmt.Errorf("Tarball too short")
 			}
 			return err
-		} else {
-			totalN += n
-			utils.Debugf("[tar autodetect] n: %d", n)
 		}
+		totalN += n
+		utils.Debugf("[tar autodetect] n: %d", n)
 	}
+
 	compression := DetectCompression(buf)
 
 	utils.Debugf("Archive compression detected: %s", compression.Extension())

+ 2 - 3
auth/auth.go

@@ -196,10 +196,9 @@ func Login(authConfig *AuthConfig, factory *utils.HTTPRequestFactory) (string, e
 		if loginAgainstOfficialIndex {
 			return "", fmt.Errorf("Login: Your account hasn't been activated. " +
 				"Please check your e-mail for a confirmation link.")
-		} else {
-			return "", fmt.Errorf("Login: Your account hasn't been activated. " +
-				"Please see the documentation of the registry " + serverAddress + " for instructions how to activate it.")
 		}
+		return "", fmt.Errorf("Login: Your account hasn't been activated. " +
+			"Please see the documentation of the registry " + serverAddress + " for instructions how to activate it.")
 	} else if reqStatusCode == 400 {
 		if string(reqBody) == "\"Username or email already exists\"" {
 			req, err := factory.NewRequest("GET", serverAddress+"users/", nil)

+ 3 - 4
commands.go

@@ -2073,10 +2073,9 @@ func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, h
 
 	if matchesContentType(resp.Header.Get("Content-Type"), "application/json") {
 		return utils.DisplayJSONMessagesStream(resp.Body, out)
-	} else {
-		if _, err := io.Copy(out, resp.Body); err != nil {
-			return err
-		}
+	}
+	if _, err := io.Copy(out, resp.Body); err != nil {
+		return err
 	}
 	return nil
 }

+ 3 - 4
graph.go

@@ -220,12 +220,11 @@ func (graph *Graph) getDockerInitLayer() (string, error) {
 					if err := os.MkdirAll(path.Join(initLayer, path.Dir(pth)), 0755); err != nil {
 						return "", err
 					}
-
-					if f, err := os.OpenFile(path.Join(initLayer, pth), os.O_CREATE, 0755); err != nil {
+					f, err := os.OpenFile(path.Join(initLayer, pth), os.O_CREATE, 0755)
+					if err != nil {
 						return "", err
-					} else {
-						f.Close()
 					}
+					f.Close()
 				}
 			} else {
 				return "", err

+ 25 - 24
image.go

@@ -54,11 +54,11 @@ func LoadImage(root string) (*Image, error) {
 			return nil, err
 		}
 	} else {
-		if size, err := strconv.Atoi(string(buf)); err != nil {
+		size, err := strconv.Atoi(string(buf))
+		if err != nil {
 			return nil, err
-		} else {
-			img.Size = int64(size)
 		}
+		img.Size = int64(size)
 	}
 
 	// Check that the filesystem layer exists
@@ -99,14 +99,14 @@ func StoreImage(img *Image, jsonData []byte, layerData archive.Archive, root str
 	// If raw json is provided, then use it
 	if jsonData != nil {
 		return ioutil.WriteFile(jsonPath(root), jsonData, 0600)
-	} else { // Otherwise, unmarshal the image
-		jsonData, err := json.Marshal(img)
-		if err != nil {
-			return err
-		}
-		if err := ioutil.WriteFile(jsonPath(root), jsonData, 0600); err != nil {
-			return err
-		}
+	}
+	// Otherwise, unmarshal the image
+	jsonData, err := json.Marshal(img)
+	if err != nil {
+		return err
+	}
+	if err := ioutil.WriteFile(jsonPath(root), jsonData, 0600); err != nil {
+		return err
 	}
 
 	return StoreSize(img, root)
@@ -115,7 +115,7 @@ func StoreImage(img *Image, jsonData []byte, layerData archive.Archive, root str
 func StoreSize(img *Image, root string) error {
 	layer := layerPath(root)
 
-	var totalSize int64 = 0
+	var totalSize int64
 	filepath.Walk(layer, func(path string, fileInfo os.FileInfo, err error) error {
 		totalSize += fileInfo.Size()
 		return nil
@@ -163,21 +163,21 @@ func MountAUFS(ro []string, rw string, target string) error {
 }
 
 // TarLayer returns a tar archive of the image's filesystem layer.
-func (image *Image) TarLayer(compression archive.Compression) (archive.Archive, error) {
-	layerPath, err := image.layer()
+func (img *Image) TarLayer(compression archive.Compression) (archive.Archive, error) {
+	layerPath, err := img.layer()
 	if err != nil {
 		return nil, err
 	}
 	return archive.Tar(layerPath, compression)
 }
 
-func (image *Image) Mount(root, rw string) error {
+func (img *Image) Mount(root, rw string) error {
 	if mounted, err := Mounted(root); err != nil {
 		return err
 	} else if mounted {
 		return fmt.Errorf("%s is already mounted", root)
 	}
-	layers, err := image.layers()
+	layers, err := img.layers()
 	if err != nil {
 		return err
 	}
@@ -194,8 +194,8 @@ func (image *Image) Mount(root, rw string) error {
 	return nil
 }
 
-func (image *Image) Changes(rw string) ([]Change, error) {
-	layers, err := image.layers()
+func (img *Image) Changes(rw string) ([]Change, error) {
+	layers, err := img.layers()
 	if err != nil {
 		return nil, err
 	}
@@ -241,8 +241,10 @@ func (img *Image) History() ([]*Image, error) {
 // FIXME: @shykes refactor this function with the new error handling
 //        (I'll do it if I have time tonight, I focus on the rest)
 func (img *Image) layers() ([]string, error) {
-	var list []string
-	var e error
+	var (
+		list []string
+		e    error
+	)
 	if err := img.WalkHistory(
 		func(img *Image) (err error) {
 			if layer, err := img.layer(); err != nil {
@@ -262,12 +264,11 @@ func (img *Image) layers() ([]string, error) {
 	}
 
 	// Inject the dockerinit layer (empty place-holder for mount-binding dockerinit)
-	if dockerinitLayer, err := img.getDockerInitLayer(); err != nil {
+	dockerinitLayer, err := img.getDockerInitLayer()
+	if err != nil {
 		return nil, err
-	} else {
-		list = append([]string{dockerinitLayer}, list...)
 	}
-	return list, nil
+	return append([]string{dockerinitLayer}, list...), nil
 }
 
 func (img *Image) WalkHistory(handler func(*Image) error) (err error) {

+ 1 - 1
runtime.go

@@ -1,7 +1,7 @@
 package docker
 
 import (
-	_ "code.google.com/p/gosqlite/sqlite3"
+	_ "code.google.com/p/gosqlite/sqlite3" // registers sqlite
 	"container/list"
 	"database/sql"
 	"fmt"

+ 10 - 8
server.go

@@ -422,9 +422,9 @@ func (srv *Server) ImageHistory(name string) ([]APIHistory, error) {
 
 }
 
-func (srv *Server) ContainerTop(name, ps_args string) (*APITop, error) {
+func (srv *Server) ContainerTop(name, psArgs string) (*APITop, error) {
 	if container := srv.runtime.Get(name); container != nil {
-		output, err := exec.Command("lxc-ps", "--name", container.ID, "--", ps_args).CombinedOutput()
+		output, err := exec.Command("lxc-ps", "--name", container.ID, "--", psArgs).CombinedOutput()
 		if err != nil {
 			return nil, fmt.Errorf("lxc-ps: %s (%s)", err, output)
 		}
@@ -891,12 +891,13 @@ func (srv *Server) pushRepository(r *registry.Registry, out io.Writer, localName
 					out.Write(sf.FormatStatus("", "Image %s already pushed, skipping", elem.ID))
 					continue
 				}
-				if checksum, err := srv.pushImage(r, out, remoteName, elem.ID, ep, repoData.Tokens, sf); err != nil {
+				checksum, err := srv.pushImage(r, out, remoteName, elem.ID, ep, repoData.Tokens, sf)
+				if err != nil {
 					// FIXME: Continue on error?
 					return err
-				} else {
-					elem.Checksum = checksum
 				}
+				elem.Checksum = checksum
+
 				if err := pushTags(); err != nil {
 					return err
 				}
@@ -939,11 +940,12 @@ func (srv *Server) pushImage(r *registry.Registry, out io.Writer, remote, imgID,
 	defer os.RemoveAll(layerData.Name())
 
 	// Send the layer
-	if checksum, err := r.PushImageLayerRegistry(imgData.ID, utils.ProgressReader(layerData, int(layerData.Size), out, sf.FormatProgress("", "Pushing", "%8v/%v (%v)"), sf, false), ep, token, jsonRaw); err != nil {
+	checksum, err = r.PushImageLayerRegistry(imgData.ID, utils.ProgressReader(layerData, int(layerData.Size), out, sf.FormatProgress("", "Pushing", "%8v/%v (%v)"), sf, false), ep, token, jsonRaw)
+	if err != nil {
 		return "", err
-	} else {
-		imgData.Checksum = checksum
 	}
+	imgData.Checksum = checksum
+
 	out.Write(sf.FormatStatus("", ""))
 
 	// Send the checksum

+ 11 - 11
utils/http.go

@@ -81,12 +81,12 @@ func NewHTTPUserAgentDecorator(versions ...VersionInfo) HTTPRequestDecorator {
 	return ret
 }
 
-func (self *HTTPUserAgentDecorator) ChangeRequest(req *http.Request) (newReq *http.Request, err error) {
+func (h *HTTPUserAgentDecorator) ChangeRequest(req *http.Request) (newReq *http.Request, err error) {
 	if req == nil {
 		return req, nil
 	}
 
-	userAgent := appendVersions(req.UserAgent(), self.versions...)
+	userAgent := appendVersions(req.UserAgent(), h.versions...)
 	if len(userAgent) > 0 {
 		req.Header.Set("User-Agent", userAgent)
 	}
@@ -97,11 +97,11 @@ type HTTPMetaHeadersDecorator struct {
 	Headers map[string][]string
 }
 
-func (self *HTTPMetaHeadersDecorator) ChangeRequest(req *http.Request) (newReq *http.Request, err error) {
-	if self.Headers == nil {
+func (h *HTTPMetaHeadersDecorator) ChangeRequest(req *http.Request) (newReq *http.Request, err error) {
+	if h.Headers == nil {
 		return req, nil
 	}
-	for k, v := range self.Headers {
+	for k, v := range h.Headers {
 		req.Header[k] = v
 	}
 	return req, nil
@@ -114,25 +114,25 @@ type HTTPRequestFactory struct {
 }
 
 func NewHTTPRequestFactory(d ...HTTPRequestDecorator) *HTTPRequestFactory {
-	ret := new(HTTPRequestFactory)
-	ret.decorators = d
-	return ret
+	return &HTTPRequestFactory{
+		decorators: d,
+	}
 }
 
 // NewRequest() creates a new *http.Request,
 // applies all decorators in the HTTPRequestFactory on the request,
 // then applies decorators provided by d on the request.
-func (self *HTTPRequestFactory) NewRequest(method, urlStr string, body io.Reader, d ...HTTPRequestDecorator) (*http.Request, error) {
+func (h *HTTPRequestFactory) NewRequest(method, urlStr string, body io.Reader, d ...HTTPRequestDecorator) (*http.Request, error) {
 	req, err := http.NewRequest(method, urlStr, body)
 	if err != nil {
 		return nil, err
 	}
 
 	// By default, a nil factory should work.
-	if self == nil {
+	if h == nil {
 		return req, nil
 	}
-	for _, dec := range self.decorators {
+	for _, dec := range h.decorators {
 		req, err = dec.ChangeRequest(req)
 		if err != nil {
 			return nil, err

+ 6 - 6
utils/utils.go

@@ -1123,7 +1123,7 @@ func (graph *DependencyGraph) GenerateTraversalMap() ([][]string, error) {
 	for len(processed) < len(graph.nodes) {
 		// Use a temporary buffer for processed nodes, otherwise
 		// nodes that depend on each other could end up in the same round.
-		tmp_processed := []*DependencyNode{}
+		tmpProcessed := []*DependencyNode{}
 		for _, node := range graph.nodes {
 			// If the node has more dependencies than what we have cleared,
 			// it won't be valid for this round.
@@ -1137,7 +1137,7 @@ func (graph *DependencyGraph) GenerateTraversalMap() ([][]string, error) {
 			// It's not been processed yet and has 0 deps. Add it!
 			// (this is a shortcut for what we're doing below)
 			if node.Degree() == 0 {
-				tmp_processed = append(tmp_processed, node)
+				tmpProcessed = append(tmpProcessed, node)
 				continue
 			}
 			// If at least one dep hasn't been processed yet, we can't
@@ -1151,17 +1151,17 @@ func (graph *DependencyGraph) GenerateTraversalMap() ([][]string, error) {
 			}
 			// All deps have already been processed. Add it!
 			if ok {
-				tmp_processed = append(tmp_processed, node)
+				tmpProcessed = append(tmpProcessed, node)
 			}
 		}
-		Debugf("Round %d: found %d available nodes", len(result), len(tmp_processed))
+		Debugf("Round %d: found %d available nodes", len(result), len(tmpProcessed))
 		// If no progress has been made this round,
 		// that means we have circular dependencies.
-		if len(tmp_processed) == 0 {
+		if len(tmpProcessed) == 0 {
 			return nil, fmt.Errorf("Could not find a solution to this dependency graph")
 		}
 		round := []string{}
-		for _, nd := range tmp_processed {
+		for _, nd := range tmpProcessed {
 			round = append(round, nd.id)
 			processed[nd] = true
 		}