@@ -210,3 +210,91 @@ func GetTreeList(ctx context.Context, repo *repo_model.Repository, treePath stri
210210
211211 return treeList , nil
212212}
213+
214+ // GetTreeInformation returns the first level directories and files and all the trees of the path to treePath.
215+ // If treePath is a directory, list all subdirectories and files of treePath.
216+ func GetTreeInformation (ctx context.Context , repo * repo_model.Repository , treePath string , ref git.RefName ) ([]* TreeEntry , error ) {
217+ if repo .IsEmpty {
218+ return nil , nil
219+ }
220+ if ref == "" {
221+ ref = git .RefNameFromBranch (repo .DefaultBranch )
222+ }
223+
224+ // Check that the path given in opts.treePath is valid (not a git path)
225+ cleanTreePath := CleanUploadFileName (treePath )
226+ if cleanTreePath == "" && treePath != "" {
227+ return nil , ErrFilenameInvalid {
228+ Path : treePath ,
229+ }
230+ }
231+ treePath = cleanTreePath
232+
233+ gitRepo , closer , err := gitrepo .RepositoryFromContextOrOpen (ctx , repo )
234+ if err != nil {
235+ return nil , err
236+ }
237+ defer closer .Close ()
238+
239+ // Get the commit object for the ref
240+ commit , err := gitRepo .GetCommit (ref .String ())
241+ if err != nil {
242+ return nil , err
243+ }
244+
245+ // get root entries
246+ rootEntry , err := commit .GetTreeEntryByPath ("" )
247+ if err != nil {
248+ return nil , err
249+ }
250+ rootEntries , err := rootEntry .Tree ().ListEntries ()
251+ if err != nil {
252+ return nil , err
253+ }
254+
255+ var treeList []* TreeEntry
256+ for _ , rootEntry := range rootEntries {
257+ treeList = append (treeList , & TreeEntry {
258+ Name : rootEntry .Name (),
259+ IsFile : rootEntry .Mode () != git .EntryModeTree ,
260+ Path : rootEntry .Name (),
261+ })
262+ }
263+
264+ if treePath == "" {
265+ return treeList , nil
266+ }
267+
268+ listEntry , err := commit .GetTreeEntryByPath (treePath )
269+ if err != nil {
270+ return nil , err
271+ }
272+
273+ dir := treePath
274+ // list current entry or parent entry if it's a file's children
275+ // If the entry is a file, we return a FileContentResponse object
276+ if listEntry .IsRegular () {
277+ dir = path .Dir (treePath )
278+ if dir == "" {
279+ return treeList , nil
280+ }
281+ listEntry , err = commit .GetTreeEntryByPath (dir )
282+ if err != nil {
283+ return nil , err
284+ }
285+ }
286+
287+ entries , err := listEntry .Tree ().ListEntries ()
288+ if err != nil {
289+ return nil , err
290+ }
291+
292+ for _ , entry := range entries {
293+ treeList = append (treeList , & TreeEntry {
294+ Name : entry .Name (),
295+ IsFile : entry .Mode () != git .EntryModeTree ,
296+ Path : path .Join (treePath , entry .Name ()),
297+ })
298+ }
299+ return treeList , nil
300+ }
0 commit comments