【问题标题】:github - How to get file list under directory on github pages?github - 如何获取 github 页面目录下的文件列表?
【发布时间】:2018-05-30 09:27:34
【问题描述】:

假设一个 repo myname/myrepo 启用了 github 页面,那么 myname.github.io/myrepo 将可用,托管与原始 repo 相同的内容,而无需任何专门的部署。

repo
  |-- folder
        |-- file1
        |-- file2

我希望发送像 myname.github.io/myrepo/folder 这样的 http 请求来动态获取像 ['file1', 'file2'] 这样的东西(甚至只是一个我可以通过 javascript 解析的字符串),比如 nginx autoindex。

我怎样才能做到这一点?

注意:我知道我可以编写一个脚本,可能使用任何语言,如 bash、python、ruby、perl,可以无止境地命名,以生成索引文件。我不想要任何额外的部署,即使是 CI。

【问题讨论】:

标签: github github-pages


【解决方案1】:

octotree(github的chrome插件)启发,发送APIGET https://api.github.com/repos/{owner}/{repo}/git/trees/master获取根文件夹结构并递归访问"type": "tree"的子级。

由于 github API 的速率限制为 5000 个请求/小时,这可能不适合深树和宽树。

【讨论】:

    【解决方案2】:

    目录列表 - GitHub 页面

    如果使用脚本生成索引文件不是您想要的,那么没有其他方法可以实现。

    GitHub Pages 用于允许 .PHP 文件,您可以在其中以更简单的方式执行类似操作(请参阅 here),但此功能不可用,因此上面提到的脚本会为其生成静态文件。

    我知道没有其他方法可以实现这一目标。 您为什么不想使用该脚本? (特殊原因?)请提供更多关于您可以使用的信息,以便我们找到其他方法。

    更新 1:

    我发现something 可以让它工作,但需要安装,所以你可能不喜欢它(参见下面的“*note”)。这有点过时了(最后一次提交是在 2 月)。

    *注意:大多数人都会同意,要实现您想要的,您需要一种服务器端语言,但如前所述,GHP 不支持 php。 See more here.

    【讨论】:

    • 其实我没有你看到的任何部署。如果有,那就是git push。使用脚本,每次我想添加一些东西时,我都必须记住运行脚本。那太琐碎了。我曾经以为 github 会有一个 API,结果发现它只包含一些元数据,如星号和叉子。我想像中的一个愚蠢的解决方案可能是,我编写了一个 js 脚本,在其中我向https://github.com/myname/myrepo 发送一个 HTTP 请求,然后继续。
    【解决方案3】:

    我在 GitHub Pages 上托管的项目需要这样的东西,所以显然需要使用 JavaScript。

    如果目录位于 repo 的根目录。 JavaScript 中的代码可能如下所示:

    async function list_directory(user, repo, directory) {
      const url = `https://api.github.com/repos/${user}/${repo}/git/trees/master`;
      const list = await fetch(url).then(res => res.json());
      const dir = list.tree.find(node => node.path === directory);
      if (dir) {
         const list = await fetch(dir.url).then(res => res.json());
         return list.tree.map(node => node.path);
      }
    }
    

    如果目录是嵌套的,则需要用斜杠 (/) 分割目录并使用循环获取所有目录:

    async function list_directory(user, repo, directory) {
      const url = `https://api.github.com/repos/${user}/${repo}/git/trees/master`;
      directory = directory.split('/').filter(Boolean);
      const dir = await directory.reduce(async (acc, dir) => {
          const { url } = await acc;
          const list = await fetch(url).then(res => res.json());
          return list.tree.find(node => node.path === dir);
      }, { url });
      if (dir) {
         const list = await fetch(dir.url).then(res => res.json());
         return list.tree.map(node => node.path);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 2022-12-30
      • 2022-01-24
      • 2015-09-12
      • 2021-09-14
      • 1970-01-01
      • 2019-08-12
      相关资源
      最近更新 更多