写了个脚本,下载discuzq,并解压到指定 git 仓储下,方便更新代码。
遇到一个问题,在解压 uniapp 这个zip包时,里面多了一层目录包装,如果直接解压到指定目录,也会造成多了一级目录,如下图:
那如何从zip包里解压,并去掉多余一层的目录 uniapp_v2.xxxx
,可以看下面的 copy("zip://{$zipfile}#{$filename}", $newfilename);
__dir__ . '/zips', 'uniapp' => __dir__ . '/uniapp', ]; downloadandextract('https://dl.discuz.chat/uniapp_latest.zip', 'uniapp'); function downloadandextract($zipurl, $key) { global $config; echo "正在下载: $zipurl\n"; $zipdata = file_get_contents($zipurl); $zipfile = $config->zips . "/$key-" . date('ymd-his') . '.zip'; file_put_contents($zipfile, $zipdata); echo "正在解压到 {$config->$key} \n"; $zip = new ziparchive; if ($key === 'uniapp') { if ($zip->open($zipfile) === true) { $folder = $zip->getnameindex(0); for ($i = 1; $i < $zip->numfiles; $i ) { $filename = $zip->getnameindex($i); if (substr($filename, -1, 1) === '/') { continue; } // $folder like => uniapp_v2.1.201029/ // $filename like => uniapp_v2.1.201029/commitlint.config.js $newfilename = $config->$key . '/' . str_replace($folder, '', $filename); if (!file_exists(dirname($newfilename))) { mkdir(dirname($newfilename), 0644, true); } copy("zip://{$zipfile}#{$filename}", $newfilename); } $zip->close(); } } echo "-------------- sucess --------------\n"; }