下载Apple开源项目

Apple Open Source网站上,有许多苹果公司的开源项目,然而没有类似于GitHub的打包下载,需要自己一个文件一个文件的看。这样就麻烦了,特别是稍大一点的项目。

于是就想到了做这么一个东西,用于下载Apple Open Source上的开源项目。

还好这个网站上的Source Browser页面非常有规律,毕竟是Apple嘛,用正则一下就能搞定。

不过下载文件的时候,需要在末尾加上?txt来获取纯文本内容。

使用方式:

保存这里的PHP代码,然后执行

$ php 你保存的文件名

之后依据提示输入URL即可。比如http://www.opensource.apple.com/source/adv_cmds/adv_cmds-158/

接下来它就会自己工作了~如图

屏幕快照 2015-05-15 上午10.24.04

代码如下:
(你也可以在GitHub找到这份代码,Apple Open Source Downloader)

<?php
    function get_open_source_files($open_source_URL, $sub) {
        $is_sub = false;
        if (substr($sub, strlen($sub) - 1, 1) == '/') {
            if (!file_exists($sub)) {
                mkdir($sub, 0775, true);
            }
            $is_sub = true;
        }
        $content = file_get_contents($open_source_URL);
        if ($is_sub) {
            preg_match_all('/><\/a><\/td><td><a href="(.*?)">(.*?)<\/a>/', $content, $matches);
            $URLs = $matches[1];
            $description = $matches[2];
            for ($i = 0; $i < count($URLs); $i++) {
                if ($description[$i] == 'Parent Directory') {
                    continue;
                }
                $next = $open_source_URL.$URLs[$i];
                if (substr($next, strlen($next) - 1, 1) != '/') {
                    $next .= '?txt';
                }
                get_open_source_files($next, $sub.$URLs[$i]);
            }
        } else {
            $fd = fopen($sub, 'w');
            if ($fd) {
                fwrite($fd, $content);
                print $sub." saved!\n";
            } else {
                print $sub." failed!\n";
            }
            fclose($fd);
        }
    }
    
    print "Apple Open Source URL: ";
    $open_source_URL = trim(fgets(STDIN));
    if (strpos($open_source_URL, 'http://www.opensource.apple.com/source/') === 0) {
        $paths = preg_split('/\//', $open_source_URL);
        $start = end($paths);
        if ($start == '') {
            $start = $paths[count($paths) - 2].'/';
        }
        get_open_source_files($open_source_URL, $start);
    } else {
        print "Accepts URL starting with http://www.opensource.apple.com/source/ only.\n";
    }
?>

2 thoughts on “下载Apple开源项目”

Leave a Reply

Your email address will not be published. Required fields are marked *

eight − 5 =