|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const Debug = require('debug'); |
| 4 | +const GitUrlParse = require('git-url-parse'); |
| 5 | +const Wreck = require('@hapi/wreck'); |
| 6 | + |
| 7 | +const Utils = require('../utils'); |
| 8 | + |
| 9 | + |
| 10 | +const internals = { |
| 11 | + cache: new Map(), |
| 12 | + log: Debug('detect-node-support:loader'), |
| 13 | + error: Debug('detect-node-support:error') |
| 14 | +}; |
| 15 | + |
| 16 | + |
| 17 | +exports.create = (repository) => { |
| 18 | + |
| 19 | + if (repository.split('/').length === 2) { |
| 20 | + repository = `https://github.com/${repository}`; |
| 21 | + } |
| 22 | + |
| 23 | + const parsedRepository = GitUrlParse(repository); |
| 24 | + |
| 25 | + return { |
| 26 | + getCommit: async () => { |
| 27 | + |
| 28 | + const simpleGit = Utils.simpleGit(); |
| 29 | + const httpRepository = GitUrlParse.stringify(parsedRepository, 'http'); |
| 30 | + const result = await simpleGit.listRemote([httpRepository, 'HEAD']); |
| 31 | + const [head] = result.split(/\s+/); |
| 32 | + |
| 33 | + return head; |
| 34 | + }, |
| 35 | + loadFile: async (filename, options) => { |
| 36 | + |
| 37 | + if (parsedRepository.source !== 'github.com') { |
| 38 | + throw new Error('Only github.com paths supported, feel free to PR at https://github.com/pkgjs/detect-node-support'); |
| 39 | + } |
| 40 | + |
| 41 | + const url = `https://raw.githubusercontent.com/${parsedRepository.full_name}/HEAD/${filename}`; |
| 42 | + internals.log('Loading: %s', url); |
| 43 | + |
| 44 | + if (options === undefined && internals.cache.has(url)) { |
| 45 | + internals.log('From cache: %s', url); |
| 46 | + return internals.cache.get(url); |
| 47 | + } |
| 48 | + |
| 49 | + try { |
| 50 | + const { payload } = await Wreck.get(url, options); |
| 51 | + |
| 52 | + if (options === undefined) { |
| 53 | + internals.cache.set(url, payload); |
| 54 | + } |
| 55 | + |
| 56 | + internals.log('Loaded: %s', url); |
| 57 | + return payload; |
| 58 | + } |
| 59 | + catch (err) { |
| 60 | + |
| 61 | + if (err.data && err.data.res.statusCode === 404) { |
| 62 | + internals.log('Not found: %s', url); |
| 63 | + const error = new Error(`${repository} does not contain a ${filename}`); |
| 64 | + error.code = 'ENOENT'; |
| 65 | + throw error; |
| 66 | + } |
| 67 | + |
| 68 | + internals.error('Failed to load: %s', url); |
| 69 | + throw err; |
| 70 | + } |
| 71 | + } |
| 72 | + }; |
| 73 | +}; |
| 74 | + |
| 75 | + |
| 76 | +exports.clearCache = () => { |
| 77 | + |
| 78 | + internals.cache = new Map(); |
| 79 | +}; |
0 commit comments