Beispiel #1
0
func TestCanOpenRepository(t *testing.T) {
	_, err := g.OpenRepository(".")

	if err != nil {
		t.Errorf("unable to open repository: %v", err)
	}
}
Beispiel #2
0
func Commit(path string, message string) error {

	repo, err := git.OpenRepository(".gattai")

	// TODO re-config
	signature := &git.Signature{
		Name:  "Chanwit Kaewkasi",
		Email: "*****@*****.**",
		When:  time.Now(),
	}

	idx, err := repo.Index()
	if err != nil {
		panic(err)
	}

	err = idx.AddByPath(path)
	if err != nil {
		panic(err)
	}

	treeId, err := idx.WriteTree()
	if err != nil {
		panic(err)
	}

	err = idx.Write()
	if err != nil {
		panic(err)
	}

	tree, err := repo.LookupTree(treeId)
	if err != nil {
		panic(err)
	}

	var commit *git.Oid
	head, err := repo.Head()
	if err == nil {
		headCommit, err := repo.LookupCommit(head.Target())
		if err != nil {
			panic(err)
		}

		commit, err = repo.CreateCommit("HEAD", signature, signature, message, tree, headCommit)
		if err != nil {
			panic(err)
		}

	} else {
		commit, err = repo.CreateCommit("HEAD", signature, signature, message, tree)
		if err != nil {
			panic(err)
		}
	}

	fmt.Printf("%s\n", commit)
	return err
}
Beispiel #3
0
func TestCanGetHead(t *testing.T) {
	repo, _ := g.OpenRepository(".")
	ref, _ := repo.LookupReference("HEAD")

	if ref.Name() != "HEAD" {
		t.Errorf("expected ref name to be HEAD instead of %s", ref.Name())
	}
}
Beispiel #4
0
//open repository
func (r *Repo) openRepository(loc string) {
	userRepo.location = loc
	repo, err := git.OpenRepository(userRepo.location)
	log.Println(repo)
	if err != nil {
		panic(err)
	}

	r.repo = repo
}
Beispiel #5
0
// Open opens an existing repository. See Init() for parameters.
func Open(repo, ref string) (*DB, error) {
	r, err := git.OpenRepository(repo)
	if err != nil {
		return nil, err
	}
	db, err := newRepo(r, ref)
	if err != nil {
		return nil, err
	}
	return db, nil
}
Beispiel #6
0
func Open(dir string) (*Repository, error) {
	cr, err := gitcmd.Open(dir)
	if err != nil {
		return nil, err
	}

	u, err := git2go.OpenRepository(dir)
	if err != nil {
		return nil, err
	}
	return &Repository{Repository: cr, u: u}, nil
}
Beispiel #7
0
func main() {
	repoPath := filepath.Join(os.Getenv("GOPATH"), "src/github.com/libgit2/git2go")
	gitRepo, err := git.OpenRepository(repoPath)
	if err != nil {
		log.Fatal(err)
	}
	commitOid, err := gitRepo.Head()
	if err != nil {
		log.Fatal(err)
	}
	C
}
func prepareRepo(t *testing.T) *gg.Repository {
	dir, err := os.Getwd()
	if err != nil {
		t.Errorf("Unable to open repo directory: '%v'\n", err)
		t.FailNow()
	}

	repo, err := gg.OpenRepository(dir + "/..")
	if err != nil {
		t.Errorf("Unable to open repository: '%v'\n", err)
		t.FailNow()
	}

	return repo
}
Beispiel #9
0
func main() {
	project := flag.String("project", "", "URL to the project")
	flag.Parse()

	// Check if project url passed
	if *project == "" {
		fmt.Printf("Usage: wain -project <project-url>\n")
		os.Exit(0)
	}

	// Load the config
	cfg := config.Load()

	// Check if we have write permissions to apps folder
	info, err := os.Stat(cfg.Defaults.AppFolder)
	if os.IsNotExist(err) {
		err = os.Mkdir(cfg.Defaults.AppFolder, 0700)

		if err != nil {
			log.Fatalf("Unable to create folder '%v'. Error: %v", cfg.Defaults.AppFolder, err)
			os.Exit(1)
		}
	} else if err != nil {
		log.Fatalf("Unable to open folder '%v'. Error %v", cfg.Defaults.AppFolder, err)
		os.Exit(1)
	} else if !info.IsDir() {
		log.Fatalf("'%v' is not a folder.", cfg.Defaults.AppFolder)
		os.Exit(1)
	}

	// Attempt to checkout the project
	_, err = git.OpenRepository(*project)

	if err != nil {
		log.Fatalf("Unable to clone the repo. Error: %v", err)
		os.Exit(1)
	}

	// Determine type

	fmt.Printf("Gonna fetch %v...\n", *project)
}
Beispiel #10
0
func OpenCodebase(localPath string) (model.Codebase, error) {
	repo, err := git2go.OpenRepository(localPath)
	if err != nil {
		return nil, err
	}

	config, err := repo.Config()
	if err != nil {
		return nil, err
	}

	originURL, err := config.LookupString("remote.origin.url")
	if err == nil {
		originURL = ""
	}

	return &Codebase{
		repo:      repo,
		originURL: originURL,
	}, nil
}
Beispiel #11
0
func v1CompatGetTreeId(repositoryPath string) (string, error) {
	repository, err := git.OpenRepository(repositoryPath)
	if err != nil {
		return "", err
	}
	defer repository.Free()
	headRef, err := repository.Head()
	if err != nil {
		return "", err
	}
	defer headRef.Free()
	headObject, err := headRef.Peel(git.ObjectCommit)
	if err != nil {
		return "", err
	}
	defer headObject.Free()
	headCommit, err := headObject.AsCommit()
	if err != nil {
		return "", err
	}
	defer headCommit.Free()
	return headCommit.TreeId().String(), nil
}
Beispiel #12
0
func (d Differ) Diff(workingDir string) []string {
	var repo *git.Respository
	var index *git.Index
	var diff *git.Diff
	var differentFiles []string
	var err error

	if repo, err = git.OpenRepository(workingDir); err != nil {
		log.Fatal(err)
		return nil
	}

	if index, err = git.OpenIndex(workingDir); err != nil {
		log.Fatal(err)
		return nil
	}

	if diff, err = repo.DiffIndexToWorkdir(index, nil); err != nil {
		log.Fatal(err)
		return nil
	}

	// TODO actually do diff
}
Beispiel #13
0
// Returns a TreeFS for the given repository. The uri must have the format REPO-DIR:TREEISH.
func NewGitFSRoot(uri string, opts *GitFSOptions) (nodefs.Node, error) {
	components := strings.Split(uri, ":")
	if len(components) != 2 {
		return nil, fmt.Errorf("must have 2 components: %q", uri)
	}

	if fi, err := os.Lstat(components[0]); err != nil {
		return nil, err
	} else if !fi.IsDir() {
		return nil, syscall.ENOTDIR
	}

	repo, err := git.OpenRepository(components[0])
	if err != nil {
		return nil, err
	}

	root, err := NewTreeFSRoot(repo, components[1], opts)
	if err != nil {
		return nil, err
	}

	return root, nil
}
Beispiel #14
0
func gitOriginURL(project *Project) string {
	repo, _ := git.OpenRepository(project.Directory)
	config, _ := repo.Config()
	url, _ := config.LookupString("remote.origin.url")
	return url
}
Beispiel #15
0
func doGitStuff() {
	signature := &git.Signature{
		Name:  "David Calavera",
		Email: "*****@*****.**",
		When:  time.Now(),
	}

	files, _ := ioutil.ReadDir("/Users/alex/go/src/github.com/repo/")
	for _, f := range files {
		log.Println(f.Name())
	}
	repo, err := git.OpenRepository("/Users/alex/go/src/github.com/repo/")
	log.Println(repo)
	if err != nil {
		panic(err)
	}

	//get the head:
	head, err := repo.Head()
	if err != nil {
		panic(err)
	}

	headCommit, err := repo.LookupCommit(head.Target())
	if err != nil {
		panic(err)
	}
	//create a branch
	var branch *git.Branch
	branch, err = repo.CreateBranch("whatisthename", headCommit, false)
	if err != nil {
		panic(err)
	}

	//add a file to the staging area:
	idx, err := repo.Index()
	if err != nil {
		panic(err)
	}

	err = idx.AddByPath("storage.txt")
	if err != nil {
		panic(err)
	}

	treeId, err := idx.WriteTree()
	if err != nil {
		panic(err)
	}

	err = idx.Write()
	if err != nil {
		panic(err)
	}
	//commit the change:
	tree, err := repo.LookupTree(treeId)
	if err != nil {
		panic(err)
	}

	commitTarget, err := repo.LookupCommit(branch.Target())
	if err != nil {
		panic(err)
	}

	message := "What a day"
	_, err = repo.CreateCommit("refs/heads/whatisthename", signature, signature, message, tree, commitTarget)
	if err != nil {
		panic(err)
	}
}
Beispiel #16
0
func NewManifestFS(m *manifest.Manifest, repoRoot string, gitOpts *GitFSOptions) (nodefs.Node, error) {
	filtered := *m
	filtered.Project = nil
	for _, p := range m.Project {
		if p.Groups["notdefault"] {
			continue
		}
		filtered.Project = append(filtered.Project, p)
	}

	root := &manifestFSRoot{
		Node:     nodefs.NewDefaultNode(),
		repoMap:  map[string]nodefs.Node{},
		manifest: filtered,
	}

	type result struct {
		name string
		node nodefs.Node
		err  error
	}

	ch := make(chan result, len(root.manifest.Project))
	for _, p := range root.manifest.Project {
		go func(p manifest.Project) {
			// the spec isn't clear about this, but the git repo
			// is placed locally at p.Path rather than p.Name
			repo, err := git.OpenRepository(filepath.Join(repoRoot, p.Path) + ".git")
			if err != nil {
				ch <- result{err: err}
				return
			}

			remote := p.Remote
			revision := p.Revision
			if revision == "" {
				revision = root.manifest.Default.Revision
			}
			if remote == "" {
				remote = root.manifest.Remote.Name
			}

			commit := filepath.Join(remote, revision)
			projectRoot, err := NewTreeFSRoot(repo, commit, gitOpts)
			ch <- result{p.Name, projectRoot, err}
		}(p)
	}

	var firstError error
	for _ = range root.manifest.Project {
		res := <-ch
		if firstError != nil {
			continue
		}
		if res.err != nil {
			firstError = res.err
		} else {
			root.repoMap[res.name] = res.node
		}
	}
	if firstError != nil {
		return nil, firstError
	}
	return root, nil
}
Beispiel #17
0
func main() {
	showFiles := flag.Bool("show-files", false, "Show changed files for reviewing")
	verbose := flag.Bool("verbose", false, "Show progress and errors information")
	force := flag.Bool("force", false, "Continue processing despite checks or errors")
	since := flag.String("since", "", "Consider commits after date when finding"+
		" reviewers. Defaults to 6 months ago (format 'YYYY-MM-DD')")
	ie := flag.String("ignore-extension", "", "Exclude changed paths that end with"+
		" these extensions (--ignore-extension svg,png,jpg)")
	oe := flag.String("only-extension", "", "Only consider changed paths that end with"+
		" one of these extensions (--only-extension go,js)")
	ip := flag.String("ignore-path", "", "Exclude file or files under path"+
		" (--ignore-path main.go,src)")
	op := flag.String("only-path", "", "Only consider file or files under path"+
		" (--only-path main.go,src)")

	flag.Parse()

	spaceOrComma := func(r rune) bool {
		switch r {
		case ' ', ',':
			return true
		}
		return false
	}

	ignoredExtensions := strings.FieldsFunc(*ie, spaceOrComma)
	onlyExtensions := strings.FieldsFunc(*oe, spaceOrComma)
	ignoredPaths := strings.FieldsFunc(*ip, spaceOrComma)
	onlyPaths := strings.FieldsFunc(*op, spaceOrComma)

	err := checkDateArg(*since)
	if len(*since) > 0 && err != nil {
		fmt.Println("Problem with input format for 'since' argument. Run 'git reviewer -h'")
		return
	}

	dir, err := os.Getwd()
	if err != nil {
		fmt.Printf("Unable to open current directory: %v\n", err)
		return
	}

	repo, err := gg.OpenRepository(dir)
	if err != nil {
		fmt.Printf("Unable to open repository: %v\n", err)
		return
	}

	r := gr.Reviewer{
		Repo:              repo,
		ShowFiles:         *showFiles,
		Verbose:           *verbose,
		Since:             *since,
		IgnoredExtensions: ignoredExtensions,
		OnlyExtensions:    onlyExtensions,
		IgnoredPaths:      ignoredPaths,
		OnlyPaths:         onlyPaths,
	}

	// Determine if branch is reviewable
	if behind, err := r.BranchBehind(); behind || err != nil {
		if err != nil {
			fmt.Printf("There was an error determining branch state: %v\n", err)
			return
		}

		fmt.Println("Current branch is behind master. Merge up!")
		if *force == false {
			return
		}
	}

	// Find changed files in this branch.
	files, err := r.FindFiles()

	if err != nil {
		fmt.Printf("There was an error finding files: %v\n", err)
		return
	}

	if len(files) == 0 {
		fmt.Println("No changes on this branch!")
		return
	}

	if *showFiles {
		fmt.Println("Reviewers across the following changed files:")
		for _, file := range files {
			fmt.Printf("  %s\n", file)
		}
		fmt.Println()
	}

	// Find the best reviewers for these files.
	reviewers, err := r.FindReviewers(files)
	if err != nil {
		fmt.Printf("There was an error finding reviewers: %v\n", err)
		return
	}

	var buffer bytes.Buffer
	buffer.WriteString("Reviewers:\n")
	buffer.WriteString(reviewers)
	fmt.Println(buffer.String())
}
Beispiel #18
0
// Git2goRepo returns the git2go.Repository struct from the Repository's path.
func (r *Repository) Git2goRepo() (*git.Repository, error) {
	repo, err := git.OpenRepository(r.Path)
	return repo, err
}
Beispiel #19
0
func (input *GraderInput) createArchiveFromGit(archivePath string) (int64, error) {
	repository, err := git.OpenRepository(input.repositoryPath)
	if err != nil {
		return 0, err
	}
	defer repository.Free()

	treeOid, err := git.NewOid(input.Hash())
	if err != nil {
		return 0, err
	}

	tree, err := repository.LookupTree(treeOid)
	if err != nil {
		return 0, err
	}
	defer tree.Free()
	odb, err := repository.Odb()
	if err != nil {
		return 0, err
	}
	defer odb.Free()

	tmpFd, err := os.Create(archivePath)
	if err != nil {
		return 0, err
	}
	defer tmpFd.Close()

	gz := gzip.NewWriter(tmpFd)
	defer gz.Close()

	archive := tar.NewWriter(gz)
	defer archive.Close()

	var walkErr error = nil
	foundSettings := false
	var uncompressedSize int64 = 0
	tree.Walk(func(parent string, entry *git.TreeEntry) int {
		entryPath := path.Join(parent, entry.Name)
		if entryPath == "settings.json" {
			foundSettings = true
		}
		switch entry.Type {
		case git.ObjectTree:
			hdr := &tar.Header{
				Name:     entryPath,
				Typeflag: tar.TypeDir,
				Mode:     0755,
				Size:     0,
			}
			if walkErr = archive.WriteHeader(hdr); walkErr != nil {
				return -1
			}
		case git.ObjectBlob:
			blob, walkErr := repository.LookupBlob(entry.Id)
			if walkErr != nil {
				return -1
			}
			defer blob.Free()

			hdr := &tar.Header{
				Name:     entryPath,
				Typeflag: tar.TypeReg,
				Mode:     0644,
				Size:     blob.Size(),
			}
			uncompressedSize += blob.Size()
			if walkErr = archive.WriteHeader(hdr); walkErr != nil {
				return -1
			}

			stream, err := odb.NewReadStream(entry.Id)
			if err == nil {
				defer stream.Free()
				if _, walkErr := io.Copy(archive, stream); walkErr != nil {
					return -1
				}
			} else {
				// That particular object cannot be streamed. Allocate the blob in
				// memory and write it to the archive.
				if _, walkErr := archive.Write(blob.Contents()); walkErr != nil {
					return -1
				}
			}
		}
		return 0
	})

	if walkErr != nil {
		return 0, walkErr
	}
	if !foundSettings {
		return 0, fmt.Errorf(
			"Could not find `settings.json` in %s:%s",
			input.repositoryPath,
			input.Hash(),
		)
	}
	return uncompressedSize, nil
}
Beispiel #20
0
func (input *v1CompatGraderInput) createArchiveFromGit(
	archivePath string,
) (int64, error) {
	err := input.db.QueryRow(
		`SELECT
			extra_wall_time, memory_limit, output_limit, overall_wall_time_limit,
			time_limit, validator_time_limit, slow, validator
		FROM
			Problems
		WHERE
			alias = ?;`, input.problemName).Scan(
		&input.Settings().Limits.ExtraWallTime,
		&input.Settings().Limits.MemoryLimit,
		&input.Settings().Limits.OutputLimit,
		&input.Settings().Limits.OverallWallTimeLimit,
		&input.Settings().Limits.TimeLimit,
		&input.Settings().Limits.ValidatorTimeLimit,
		&input.Settings().Slow,
		&input.Settings().Validator.Name,
	)
	if err != nil {
		return 0, err
	}
	input.Settings().Limits.MemoryLimit *= 1024
	if input.Settings().Validator.Name == "token-numeric" {
		tolerance := 1e-6
		input.Settings().Validator.Tolerance = &tolerance
	}

	repository, err := git.OpenRepository(input.repositoryPath)
	if err != nil {
		return 0, err
	}
	defer repository.Free()

	treeOid, err := git.NewOid(input.Hash())
	if err != nil {
		return 0, err
	}

	tree, err := repository.LookupTree(treeOid)
	if err != nil {
		return 0, err
	}
	defer tree.Free()
	odb, err := repository.Odb()
	if err != nil {
		return 0, err
	}
	defer odb.Free()

	tmpFd, err := os.Create(archivePath)
	if err != nil {
		return 0, err
	}
	defer tmpFd.Close()

	gz := gzip.NewWriter(tmpFd)
	defer gz.Close()

	archive := tar.NewWriter(gz)
	defer archive.Close()

	// TODO(lhchavez): Support libinteractive.
	var walkErr error = nil
	var uncompressedSize int64 = 0
	rawCaseWeights := make(map[string]float64)
	tree.Walk(func(parent string, entry *git.TreeEntry) int {
		untrimmedPath := path.Join(parent, entry.Name)
		if untrimmedPath == "testplan" && entry.Type == git.ObjectBlob {
			blob, walkErr := repository.LookupBlob(entry.Id)
			if walkErr != nil {
				return -1
			}
			defer blob.Free()
			testplanRe := regexp.MustCompile(`^\s*([^# \t]+)\s+([0-9.]+).*$`)
			for _, line := range strings.Split(string(blob.Contents()), "\n") {
				m := testplanRe.FindStringSubmatch(line)
				if m == nil {
					continue
				}
				rawCaseWeights[m[1]], walkErr = strconv.ParseFloat(m[2], 64)
				if walkErr != nil {
					return -1
				}
			}
		}
		if strings.HasPrefix(untrimmedPath, "validator.") &&
			input.Settings().Validator.Name == "custom" &&
			entry.Type == git.ObjectBlob {
			lang := filepath.Ext(untrimmedPath)
			input.Settings().Validator.Lang = &lang
			blob, walkErr := repository.LookupBlob(entry.Id)
			if walkErr != nil {
				return -1
			}
			defer blob.Free()
			hdr := &tar.Header{
				Name:     untrimmedPath,
				Typeflag: tar.TypeReg,
				Mode:     0644,
				Size:     blob.Size(),
			}
			uncompressedSize += blob.Size()
			if walkErr = archive.WriteHeader(hdr); walkErr != nil {
				return -1
			}
			if _, walkErr := archive.Write(blob.Contents()); walkErr != nil {
				return -1
			}
		}
		if !strings.HasPrefix(untrimmedPath, "cases/") {
			return 0
		}
		entryPath := strings.TrimPrefix(untrimmedPath, "cases/")
		if strings.HasPrefix(entryPath, "in/") {
			caseName := strings.TrimSuffix(strings.TrimPrefix(entryPath, "in/"), ".in")
			if _, ok := rawCaseWeights[caseName]; !ok {
				rawCaseWeights[caseName] = 1.0
			}
		}
		switch entry.Type {
		case git.ObjectTree:
			hdr := &tar.Header{
				Name:     entryPath,
				Typeflag: tar.TypeDir,
				Mode:     0755,
				Size:     0,
			}
			if walkErr = archive.WriteHeader(hdr); walkErr != nil {
				return -1
			}
		case git.ObjectBlob:
			blob, walkErr := repository.LookupBlob(entry.Id)
			if walkErr != nil {
				return -1
			}
			defer blob.Free()

			hdr := &tar.Header{
				Name:     entryPath,
				Typeflag: tar.TypeReg,
				Mode:     0644,
				Size:     blob.Size(),
			}
			uncompressedSize += blob.Size()
			if walkErr = archive.WriteHeader(hdr); walkErr != nil {
				return -1
			}

			stream, err := odb.NewReadStream(entry.Id)
			if err == nil {
				defer stream.Free()
				if _, walkErr := io.Copy(archive, stream); walkErr != nil {
					return -1
				}
			} else {
				// That particular object cannot be streamed. Allocate the blob in
				// memory and write it to the archive.
				if _, walkErr := archive.Write(blob.Contents()); walkErr != nil {
					return -1
				}
			}
		}
		return 0
	})
	if walkErr != nil {
		return 0, walkErr
	}

	// Generate the group/case settings.
	cases := make(map[string][]common.CaseSettings)
	groupWeights := make(map[string]float64)
	totalWeight := 0.0
	for _, weight := range rawCaseWeights {
		totalWeight += weight
	}
	for caseName, weight := range rawCaseWeights {
		components := strings.SplitN(caseName, ".", 2)
		groupName := components[0]
		if _, ok := groupWeights[groupName]; !ok {
			groupWeights[groupName] = 0
		}
		groupWeights[groupName] += weight / totalWeight
		if _, ok := cases[groupName]; !ok {
			cases[groupName] = make([]common.CaseSettings, 0)
		}
		cases[groupName] = append(cases[groupName], common.CaseSettings{
			Name:   caseName,
			Weight: weight / totalWeight,
		})
	}
	input.Settings().Cases = make([]common.GroupSettings, 0)
	for groupName, cases := range cases {
		sort.Sort(common.ByCaseName(cases))
		input.Settings().Cases = append(input.Settings().Cases, common.GroupSettings{
			Cases:  cases,
			Name:   groupName,
			Weight: groupWeights[groupName],
		})
	}
	sort.Sort(common.ByGroupName(input.Settings().Cases))

	// Finally, write settings.json.
	settingsBlob, err := json.MarshalIndent(input.Settings(), "", "  ")
	if err != nil {
		return 0, err
	}
	hdr := &tar.Header{
		Name:     "settings.json",
		Typeflag: tar.TypeReg,
		Mode:     0644,
		Size:     int64(len(settingsBlob)),
	}
	uncompressedSize += int64(len(settingsBlob))
	if err = archive.WriteHeader(hdr); err != nil {
		return 0, err
	}
	if _, err = archive.Write(settingsBlob); err != nil {
		return 0, err
	}

	return uncompressedSize, nil
}