fetchFilesViaGoGit clones a repo in memory using go-git and extracts files.
(opts FetchOptions)
| 59 | |
| 60 | // fetchFilesViaGoGit clones a repo in memory using go-git and extracts files. |
| 61 | func fetchFilesViaGoGit(opts FetchOptions) error { |
| 62 | r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{ |
| 63 | URL: opts.RepoURL, |
| 64 | Depth: 1, |
| 65 | }) |
| 66 | if err != nil { |
| 67 | return fmt.Errorf(i18n.T("githelper_failed_clone_repository"), err) |
| 68 | } |
| 69 | |
| 70 | ref, err := r.Head() |
| 71 | if err != nil { |
| 72 | return fmt.Errorf(i18n.T("githelper_failed_get_head"), err) |
| 73 | } |
| 74 | |
| 75 | commit, err := r.CommitObject(ref.Hash()) |
| 76 | if err != nil { |
| 77 | return fmt.Errorf(i18n.T("githelper_failed_get_commit"), err) |
| 78 | } |
| 79 | |
| 80 | tree, err := commit.Tree() |
| 81 | if err != nil { |
| 82 | return fmt.Errorf(i18n.T("githelper_failed_get_tree"), err) |
| 83 | } |
| 84 | |
| 85 | if err := os.MkdirAll(opts.DestDir, 0755); err != nil { |
| 86 | return fmt.Errorf(i18n.T("githelper_failed_create_dest_directory"), err) |
| 87 | } |
| 88 | |
| 89 | return tree.Files().ForEach(func(f *object.File) error { |
| 90 | if !strings.HasPrefix(f.Name, opts.PathPrefix) { |
| 91 | return nil |
| 92 | } |
| 93 | |
| 94 | if opts.SingleDirectory { |
| 95 | remainingPath := strings.TrimPrefix(f.Name, opts.PathPrefix) |
| 96 | if strings.Contains(remainingPath, "/") { |
| 97 | return nil |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | relativePath := strings.TrimPrefix(f.Name, opts.PathPrefix) |
| 102 | localPath := filepath.Join(opts.DestDir, relativePath) |
| 103 | |
| 104 | if err := os.MkdirAll(filepath.Dir(localPath), 0755); err != nil { |
| 105 | return err |
| 106 | } |
| 107 | |
| 108 | reader, err := f.Reader() |
| 109 | if err != nil { |
| 110 | return err |
| 111 | } |
| 112 | defer reader.Close() |
| 113 | |
| 114 | file, err := os.Create(localPath) |
| 115 | if err != nil { |
| 116 | return err |
| 117 | } |
| 118 | defer file.Close() |
no test coverage detected