09eda590f104f5a12d7274daf0f15b2ba45f74ac
[webi-installers/.git] / _common / github.js
1 'use strict';
2
3 // this may need customizations between packages
4 const osMap = {
5   macos: /\b(mac|darwin|iPhone|iOS|iPad)/i,
6   linux: /\b(linux)/i,
7   win: /\b(win|microsoft|msft)/i,
8   sunos: /\b(sun)/i,
9   aix: /\b(aix)/i
10 };
11
12 const archMap = {
13   amd64: /(amd64|x64|[_\-]64)/i,
14   x86: /\b(x86)(?![_\-]64)/i,
15   ppc64le: /\b(ppc64le)/i,
16   ppc64: /\b(ppc64)\b/i,
17   i686: /\b(i686)\b/i,
18   arm64: /\b(arm64|arm)/i,
19   armv7l: /\b(armv?7l)/i,
20   armv6l: /\b(armv?6l)/i,
21   s390x: /\b(s390x)/i
22 };
23
24 const fileExtMap = {
25   deb: /\.deb$/i,
26   pkg: /\.pkg$/i,
27   exe: /\.exe$/i,
28   msi: /\.msi$/i,
29   zip: /\.zip$/i,
30   tar: /\.(tar(\.?(gz)?)|tgz)/i,
31   '7z': /\.7;$/i
32 };
33
34 /**
35  * Gets the releases for 'ripgrep'. This function could be trimmed down and made
36  * for use with any github release.
37  *
38  * @param request
39  * @param {string} owner
40  * @param {string} repo
41  * @returns {PromiseLike<any> | Promise<any>}
42  */
43 function getAllReleases(request, owner = 'BurntSushi', repo = 'ripgrep') {
44   if (!owner) {
45     return Promise.reject('missing owner for repo');
46   }
47   if (!repo) {
48     return Promise.reject('missing repo name');
49   }
50   return request({
51     url: `https://api.github.com/repos/${owner}/${repo}/releases`,
52     json: true
53   }).then((resp) => {
54     const gHubResp = resp.body;
55     const all = {
56       releases: [],
57       download: ''
58     };
59
60     gHubResp.forEach((release) => {
61       release['assets'].forEach((asset) => {
62         // set the primary download to the first of the releases
63         if (all.download === '') {
64           all.download = asset['browser_download_url'];
65         }
66
67         const name = asset['name'];
68         const os = Object.keys(osMap).find(regKey => {
69           name.match(osMap[regKey]);
70         }) || 'linux';
71         const arch = Object.keys(archMap)
72           .find(regKey => name.match(archMap[regKey]));
73
74         let fileExt = '';
75         Object.keys(fileExtMap).find(regKey => {
76           const match = name.match(fileExtMap[regKey]);
77           if (match) {
78             fileExt = match[0];
79             return true;
80           }
81           return false;
82         });
83
84         all.releases.push({
85           download: asset['browser_download_url'],
86           date: release['published_at'],
87           version: release['tag_name'],
88           lts: !release['prerelease'],
89           ext: fileExt,
90           arch,
91           os
92         });
93       });
94     });
95
96     return all;
97   });
98 }
99
100 module.exports = getAllReleases;
101
102 if (module === require.main) {
103   getAllReleases(require('@root/request'), 'BurntSushi', 'ripgrep').then(function(all) {
104     console.log(JSON.stringify(all, null, 2));
105   });
106 }