How to use importPath method of outline Package

Best Ginkgo code snippet using outline.importPath

Run Ginkgo automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

import.go

Source: import.go Github

copy
1// Copyright 2013 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Most of the required functions were available in the
6// "golang.org/x/tools/go/ast/astutil" package, but not exported.
7// They were copied from https://github.com/golang/tools/blob/2b0845dc783e36ae26d683f4915a5840ef01ab0f/go/ast/astutil/imports.go
8
9package outline
10
11import (
12	"go/ast"
13	"strconv"
14	"strings"
15)
16
17// packageNameForImport returns the package name for the package. If the package
18// is not imported, it returns nil. "Package name" refers to `pkgname` in the
19// call expression `pkgname.ExportedIdentifier`. Examples:
20// (import path not found) -> nil
21// "import example.com/pkg/foo" -> "foo"
22// "import fooalias example.com/pkg/foo" -> "fooalias"
23// "import . example.com/pkg/foo" -> ""
24func packageNameForImport(f *ast.File, path string) *string {
25	spec := importSpec(f, path)
26	if spec == nil {
27		return nil
28	}
29	name := spec.Name.String()
30	if name == "<nil>" {
31		// If the package name is not explicitly specified,
32		// make an educated guess. This is not guaranteed to be correct.
33		lastSlash := strings.LastIndex(path, "/")
34		if lastSlash == -1 {
35			name = path
36		} else {
37			name = path[lastSlash+1:]
38		}
39	}
40	if name == "." {
41		name = ""
42	}
43	return &name
44}
45
46// importSpec returns the import spec if f imports path,
47// or nil otherwise.
48func importSpec(f *ast.File, path string) *ast.ImportSpec {
49	for _, s := range f.Imports {
50		if importPath(s) == path {
51			return s
52		}
53	}
54	return nil
55}
56
57// importPath returns the unquoted import path of s,
58// or "" if the path is not properly quoted.
59func importPath(s *ast.ImportSpec) string {
60	t, err := strconv.Unquote(s.Path.Value)
61	if err != nil {
62		return ""
63	}
64	return t
65}
66
Full Screen

github.go

Source: github.go Github

copy
1// Copyright 2015 Unknwon
2//
3// Licensed under the Apache License, Version 2.0 (the "License"): you may
4// not use this file except in compliance with the License. You may obtain
5// a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations
13// under the License.
14
15package doc
16
17import (
18	"bytes"
19	"errors"
20	"fmt"
21	"net/http"
22	"path"
23	"regexp"
24	"strings"
25	"time"
26
27	"github.com/Unknwon/com"
28
29	"github.com/Unknwon/gowalker/models"
30	"github.com/Unknwon/gowalker/modules/base"
31	"github.com/Unknwon/gowalker/modules/setting"
32)
33
34var (
35	githubRawHeader       = http.Header{"Accept": {"application/vnd.github-blob.raw"}}
36	githubRevisionPattern = regexp.MustCompile(`data-clipboard-text="[a-z0-9A-Z]+`)
37	githubPattern         = regexp.MustCompile(`^github\.com/(?P<owner>[a-z0-9A-Z_.\-]+)/(?P<repo>[a-z0-9A-Z_.\-]+)(?P<dir>/[a-z0-9A-Z_.\-/]*)?$`)
38)
39
40func getGithubRevision(importPath, tag string) (string, error) {
41	data, err := com.HttpGetBytes(Client, fmt.Sprintf("https://%s/commits/"+tag, importPath), nil)
42	if err != nil {
43		return "", fmt.Errorf("fetch revision page: %v", err)
44	}
45
46	i := bytes.Index(data, []byte(`btn-outline`))
47	if i == -1 {
48		return "", errors.New("find revision locater: not found")
49	}
50	data = data[i+1:]
51	m := githubRevisionPattern.FindSubmatch(data)
52	if m == nil {
53		return "", fmt.Errorf("find revision: not found")
54	}
55	return strings.TrimPrefix(string(m[0]), `data-clipboard-text="`), nil
56}
57
58type RepoInfo struct {
59	DefaultBranch string `json:"default_branch"`
60	Fork          bool   `json:"fork"`
61	Parent        struct {
62		FullName string `json:"full_name"`
63	} `json:"parent"`
64}
65
66type RepoCommit struct {
67	Commit struct {
68		Committer struct {
69			Date time.Time `json:"date"`
70		} `json:"committer"`
71	} `json:"commit"`
72}
73
74func getGithubDoc(match map[string]string, etag string) (_ *Package, err error) {
75	match["cred"] = setting.GitHubCredentials
76
77	repoInfo := new(RepoInfo)
78	if err := com.HttpGetJSON(Client, com.Expand("https://api.github.com/repos/{owner}/{repo}?{cred}", match), repoInfo); err != nil {
79		return nil, fmt.Errorf("get repo default branch: %v", err)
80	}
81
82	// Set default branch if not presented.
83	if len(match["tag"]) == 0 {
84		match["tag"] = repoInfo.DefaultBranch
85	}
86
87	// Check if last commit time is behind upstream for fork repository.
88	if repoInfo.Fork {
89		url := com.Expand("https://api.github.com/repos/{owner}/{repo}/commits?per_page=1&{cred}", match)
90		forkCommits := make([]*RepoCommit, 0, 1)
91		if err := com.HttpGetJSON(Client, url, &forkCommits); err != nil {
92			return nil, fmt.Errorf("get fork repository commits: %v", err)
93		}
94		if len(forkCommits) == 0 {
95			return nil, fmt.Errorf("unexpected zero number of fork repository commits: %s", url)
96		}
97
98		match["parent"] = repoInfo.Parent.FullName
99		url = com.Expand("https://api.github.com/repos/{parent}/commits?per_page=1&{cred}", match)
100		parentCommits := make([]*RepoCommit, 0, 1)
101		if err := com.HttpGetJSON(Client, url, &parentCommits); err != nil {
102			return nil, fmt.Errorf("get parent repository commits: %v", err)
103		}
104		if len(parentCommits) == 0 {
105			return nil, fmt.Errorf("unexpected zero number of parent repository commits: %s", url)
106		}
107
108		if !forkCommits[0].Commit.Committer.Date.After(parentCommits[0].Commit.Committer.Date) {
109			return nil, fmt.Errorf("commits of this fork repository are behind or equal to its parent: %s", repoInfo.Parent.FullName)
110		}
111	}
112
113	// Check revision.
114	var commit string
115	if strings.HasPrefix(match["importPath"], "gopkg.in") {
116		// FIXME: get commit ID of gopkg.in indepdently.
117		var obj struct {
118			Sha string `json:"sha"`
119		}
120
121		if err := com.HttpGetJSON(Client,
122			com.Expand("https://gopm.io/api/v1/revision?pkgname={importPath}", match), &obj); err != nil {
123			return nil, fmt.Errorf("get gopkg.in revision: %v", err)
124		}
125
126		commit = obj.Sha
127		match["tag"] = commit
128		fmt.Println(commit)
129	} else {
130		commit, err = getGithubRevision(com.Expand("github.com/{owner}/{repo}", match), match["tag"])
131		if err != nil {
132			return nil, fmt.Errorf("get revision: %v", err)
133		}
134		if commit == etag {
135			return nil, ErrPackageNotModified
136		}
137	}
138
139	// Get files.
140	var tree struct {
141		Tree []struct {
142			Url  string
143			Path string
144			Type string
145		}
146		Url string
147	}
148
149	if err := com.HttpGetJSON(Client,
150		com.Expand("https://api.github.com/repos/{owner}/{repo}/git/trees/{tag}?recursive=1&{cred}", match), &tree); err != nil {
151		return nil, fmt.Errorf("get tree: %v", err)
152	}
153
154	// Because Github API URLs are case-insensitive, we need to check that the
155	// userRepo returned from Github matches the one that we are requesting.
156	if !strings.HasPrefix(tree.Url, com.Expand("https://api.github.com/repos/{owner}/{repo}/", match)) {
157		return nil, errors.New("GitHub import path has incorrect case")
158	}
159
160	// Get source file data and subdirectories.
161	dirPrefix := match["dir"]
162	if dirPrefix != "" {
163		dirPrefix = dirPrefix[1:] + "/"
164	}
165	dirLevel := len(strings.Split(dirPrefix, "/"))
166	dirLength := len(dirPrefix)
167	dirMap := make(map[string]bool)
168	files := make([]com.RawFile, 0, 10)
169
170	for _, node := range tree.Tree {
171		// Skip directories and files in wrong directories, get them later.
172		if node.Type != "blob" || !strings.HasPrefix(node.Path, dirPrefix) {
173			continue
174		}
175
176		// Get files and check if directories have acceptable files.
177		if d, f := path.Split(node.Path); base.IsDocFile(f) {
178			// Check if file is in the directory that is corresponding to import path.
179			if d == dirPrefix {
180				files = append(files, &Source{
181					SrcName:   f,
182					BrowseUrl: com.Expand("github.com/{owner}/{repo}/blob/{tag}/{0}", match, node.Path),
183					RawSrcUrl: com.Expand("https://raw.github.com/{owner}/{repo}/{tag}/{0}?{1}", match, node.Path, setting.GitHubCredentials),
184				})
185				continue
186			}
187
188			// Otherwise, check if it's a direct sub-directory of import path.
189			if len(strings.Split(d, "/"))-dirLevel == 1 {
190				dirMap[d[dirLength:len(d)-1]] = true
191				continue
192			}
193		}
194	}
195
196	dirs := base.MapToSortedStrings(dirMap)
197
198	if len(files) == 0 && len(dirs) == 0 {
199		return nil, ErrPackageNoGoFile
200	} else if err := com.FetchFiles(Client, files, githubRawHeader); err != nil {
201		return nil, fmt.Errorf("fetch files: %v", err)
202	}
203
204	// Start generating data.
205	// IsGoSubrepo check has been placed to crawl.getDynamic.
206	w := &Walker{
207		LineFmt: "#L%d",
208		Pdoc: &Package{
209			PkgInfo: &models.PkgInfo{
210				ImportPath:  match["importPath"],
211				ProjectPath: com.Expand("github.com/{owner}/{repo}", match),
212				ViewDirPath: com.Expand("github.com/{owner}/{repo}/tree/{tag}/{importPath}", match),
213				Etag:        commit,
214				Subdirs:     strings.Join(dirs, "|"),
215			},
216		},
217	}
218
219	srcs := make([]*Source, 0, len(files))
220	srcMap := make(map[string]*Source)
221	for _, f := range files {
222		s, _ := f.(*Source)
223		srcs = append(srcs, s)
224
225		if !strings.HasSuffix(f.Name(), "_test.go") {
226			srcMap[f.Name()] = s
227		}
228	}
229
230	pdoc, err := w.Build(&WalkRes{
231		WalkDepth: WD_All,
232		WalkType:  WT_Memory,
233		WalkMode:  WM_All,
234		Srcs:      srcs,
235	})
236	if err != nil {
237		return nil, fmt.Errorf("error walking package: %v", err)
238	}
239
240	// Get stars.
241	var repoTree struct {
242		Stars int64 `json:"watchers"`
243	}
244	if err := com.HttpGetJSON(Client,
245		com.Expand("https://api.github.com/repos/{owner}/{repo}?{cred}", match), &repoTree); err != nil {
246		return nil, fmt.Errorf("get repoTree: %v", err)
247	}
248	pdoc.Stars = repoTree.Stars
249
250	return pdoc, nil
251}
252
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger importPath code on LambdaTest Cloud Grid

Execute automation tests with importPath on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)