2021年6月25日金曜日

deno infoを使用して依存ファイルをダウンロード

deno infoサブコマンドを使うと依存ファイルのURLが取得できます。
そのURLに対応するファイルをまとめてローカルフォルダに保存するサンプルを作成しました。



依存ファイルが外部ネットワークにしかない状態を避けたい


  • URLが変わるかもしれない
  • 何らかのトラブルでアクセスできなくなるかもしれない
  • インターネットアクセスを制限された環境で必要になる事があるかもしれない
などなど、可能性はわりと低いと思いますが、ゼロとは言い切れないので放置しておくのは不安です。
依存関係インスペクターを利用するためのコマンドも用意されているので、全部まとめてダウンロードできるようにしました。
function ダウンロード(URL:string): Promise<string>{
return new Promise((resolve) => {
const req = fetch(URL)
req.then(async (res) => {
return res.text()
}).then(resolve)
})
}
function infoの返り値からpath配列を取得(対象ファイル:string): Promise<string[]>{
return new Promise((resolve) => {
const p = Deno.run({cmd:['deno', 'info', 対象ファイル], stdout:'piped'})
p.output().then((uint)=>{
const decoder = new TextDecoder("utf-8");
const str = decoder.decode(uint)
const arr入力 = str.split('\n')
const re = /https?:[\w\d\/\-\][.,!@%()_={}^~`+;]+/i
const arr出力 = []
for(const 行 of arr入力){
const ma = 行.match(re)
if(!ma){
console.log('skip > ' + 行)
continue
}
arr出力.push(ma![0])
}
resolve(arr出力)
})
})
}
function 重複が無い配列にする(arr:string[]): Map<string, boolean>{
const map = new Map<string, boolean>()
for(const URL of arr){
if(map.get(URL)){ continue }
map.set(URL, true)
}
return map
}
const 対象ファイル = Deno.args[0]
infoの返り値からpath配列を取得(対象ファイル).then((arr:string[])=>{
const arrユニーク = 重複が無い配列にする(arr)
for(const URL of arrユニーク.keys()){
const pathDir = URL.replace(/[\/][^\/]+$|:/g,'').replace(/\/+/g,'/')
Deno.mkdirSync(pathDir, {recursive:true})
ダウンロード(URL).then((text)=>{
const path = pathDir + '/' + URL.match(/[\/]([^\/]+)$/)![1]
Deno.writeTextFileSync(path, text)
})
}
console.log(arrユニーク.size)
})
view raw info_dl.ts hosted with ❤ by GitHub



実行


deno run --allow-run --allow-net --allow-write info_dl.ts ts2js.ts
view raw run hosted with ❤ by GitHub



実行結果


URLを抽出する正規表現に あまり自信がないので、skipした行をconsole.log表示するようにしてあります。






これで万が一の時もimport先を修正すればスタンドアローンで実行したりコンパイルしたりできます!

0 件のコメント:

コメントを投稿