Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

How to get a list of files in a given repo with the rest api?

JA June 18, 2021

Hi, I have a project with 20 repos. I would like to get a list of file names for each repo (in the main branch -some are called 'master', some 'main'-).

How do I go about doing this?

I saw this answer in another question, but it didn't really work for me. This is specifically what I tried (to get all the files in one repo's master branch):

/rest/api/1.0/projects/{projectName}/repos/{repoName}/master/files?limit=1000

Where am I going wrong? Ideally I would like to get all files under all repos inside a given project in one call, but if that's not possible I can settle for making an API call per repo to get each of their list of files. I don't need the content, just the file names.

 

Thanks!

1 answer

0 votes
JA August 3, 2021

Alright, in the end I just devised a way to do it via JS from the browser (couldn't find any way to do this directly with the Bitbucket API):

//The way to run this script is through DevTools (Ctrl+Shift+i) > Sources > '>>' > Snippets > New snippet > copy paste the script there 
//> run it (while in https://<your-bitbucket-domain>/projects/<your-project-name>

//STEP 1: extracts the urls of all repos under <your-project-name>
let array = document.getElementsByClassName("repository-name");
let links = Array.from(array).map(x=>x.outerHTML.match(/<a[^>]+href=\"(.*?)\"[^>]*>(.*)?<\/a>/)[1]);
// console.log(links); // (25) ["/projects/<your-proj>/repos/<repo-name>/browse"...]

let repoNames = links.map(x=>x.split("/").slice(-2,-1)).flat(); //["repoA", "repoB", "repoC", ...]
console.log( repoNames)
links.forEach((x,idx)=>fetchEachRepo("https://<your-bitbucket-domain>"+x,repoNames[idx]));

//STEP 2: fetches the html of a given url and extracts repo file names 
function fetchEachRepo(url,repoName){
let parser = new DOMParser();
let htmlDoc;
let res;
fetch(url)
.then(response => response.text())
.then(data=>{
htmlDoc = parser.parseFromString(data, 'text/html');
res=Array.from(htmlDoc.getElementsByClassName("file file-row")).map(x=>x.dataset.itemName);
res.unshift(repoName);
console.log(res);
})
.catch((err)=>console.log(err));
}


//NOTES
// $('') is an alias for document.querySelector
// $$('') is an alias for document.querySelectorAll

 

The end result looks like:

['repoA', 'readme.md', 'contributing.md'...]

['repoB', '.gitignore', ...]

...

 

Hope it helps

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events