@all-contributors/cli 0.0.0-stage → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,128 @@
1
+ import inquirer from 'inquirer';
2
+
3
+ import { git } from '../util/index.js';
4
+ import { conventions } from './commit-conventions.js';
5
+
6
+ function uniqueFiles(files) {
7
+ return [...new Set(files.filter(Boolean))];
8
+ }
9
+
10
+ export const questions = [
11
+ {
12
+ type: 'input',
13
+ name: 'projectName',
14
+ message: "What's the name of the repository?",
15
+ },
16
+ {
17
+ type: 'input',
18
+ name: 'projectOwner',
19
+ message: 'Who is the owner of the repository?',
20
+ },
21
+ {
22
+ type: 'select',
23
+ name: 'repoType',
24
+ message: 'What is the repository type?',
25
+ choices: [
26
+ {
27
+ value: 'github',
28
+ name: 'GitHub',
29
+ },
30
+ {
31
+ value: 'gitlab',
32
+ name: 'GitLab',
33
+ },
34
+ ],
35
+ default: 'github',
36
+ },
37
+ {
38
+ type: 'input',
39
+ name: 'repoHost',
40
+ message: "Where is the repository hosted? Hit Enter if it's on GitHub or GitLab",
41
+ default: function (answers) {
42
+ if (answers.repoType === 'github') {
43
+ return 'https://github.com';
44
+ } else if (answers.repoType === 'gitlab') {
45
+ return 'https://gitlab.com';
46
+ }
47
+ },
48
+ },
49
+ {
50
+ type: 'input',
51
+ name: 'contributorFile',
52
+ message: 'In which file should contributors be listed?',
53
+ default: 'README.md',
54
+ },
55
+ {
56
+ type: 'confirm',
57
+ name: 'needBadge',
58
+ message: 'Do you want a badge tallying the number of contributors?',
59
+ },
60
+ {
61
+ type: 'input',
62
+ name: 'badgeFile',
63
+ message: 'In which file should the badge be shown?',
64
+ when: function (answers) {
65
+ return answers.needBadge;
66
+ },
67
+ default: function (answers) {
68
+ return answers.contributorFile;
69
+ },
70
+ },
71
+ {
72
+ type: 'input',
73
+ name: 'imageSize',
74
+ message: 'How big should the avatars be? (in px)',
75
+ filter: parseInt,
76
+ default: 100,
77
+ },
78
+ {
79
+ type: 'confirm',
80
+ name: 'commit',
81
+ message: 'Do you want this badge to auto-commit when contributors are added?',
82
+ default: true,
83
+ },
84
+ {
85
+ type: 'select',
86
+ name: 'commitConvention',
87
+ message: 'What commit convention would you want it to use?',
88
+ choices: Object.values(conventions),
89
+ default: 'angular',
90
+ },
91
+ {
92
+ type: 'confirm',
93
+ name: 'linkToUsage',
94
+ message: 'Do you want to add a footer with link to usage?',
95
+ default: true,
96
+ },
97
+ ];
98
+
99
+ export function prompt() {
100
+ return git
101
+ .getRepoInfo()
102
+ .then((repoInfo) => {
103
+ if (repoInfo) {
104
+ questions[0].default = repoInfo.projectName;
105
+ questions[1].default = repoInfo.projectOwner;
106
+ }
107
+ return inquirer.prompt(questions);
108
+ })
109
+ .then((answers) => {
110
+ return {
111
+ config: {
112
+ projectName: answers.projectName,
113
+ projectOwner: answers.projectOwner,
114
+ repoType: answers.repoType,
115
+ repoHost: answers.repoHost,
116
+ files: uniqueFiles([answers.contributorFile, answers.badgeFile]),
117
+ imageSize: answers.imageSize,
118
+ commit: answers.commit,
119
+ commitConvention: answers.commitConvention,
120
+ contributors: [],
121
+ contributorsPerLine: 7,
122
+ linkToUsage: answers.linkToUsage,
123
+ },
124
+ contributorFile: answers.contributorFile,
125
+ badgeFile: answers.badgeFile,
126
+ };
127
+ });
128
+ }
@@ -0,0 +1,119 @@
1
+ import url from 'url';
2
+
3
+ import { isValidHttpUrl, parseHttpUrl } from '../util/url.js';
4
+
5
+ /**
6
+ * Get the host based on public or enterprise GitHub.
7
+ * https://developer.github.com/enterprise/2.17/v3/#current-version
8
+ *
9
+ * @param {String} hostname - Hostname from config.
10
+ * @returns {String} - Host for GitHub API.
11
+ */
12
+ function getApiHost(hostname) {
13
+ if (!hostname) {
14
+ hostname = 'https://github.com';
15
+ }
16
+
17
+ if (hostname !== 'https://github.com') {
18
+ // Assume Github Enterprise
19
+ return url.resolve(hostname, '/api/v3');
20
+ }
21
+
22
+ return hostname.replace(/:\/\//, '://api.');
23
+ }
24
+
25
+ function getFetchHeaders(optionalPrivateToken = '') {
26
+ const fetchHeaders = {
27
+ 'User-Agent': 'node-fetch',
28
+ };
29
+
30
+ if (optionalPrivateToken && optionalPrivateToken.length > 0) {
31
+ fetchHeaders.Authorization = `token ${optionalPrivateToken}`;
32
+ }
33
+
34
+ return fetchHeaders;
35
+ }
36
+
37
+ function getNextLink(link) {
38
+ if (!link) {
39
+ return null;
40
+ }
41
+
42
+ const nextLink = link.split(',').find((s) => s.includes('rel="next"'));
43
+
44
+ if (!nextLink) {
45
+ return null;
46
+ }
47
+
48
+ return nextLink.split(';')[0].trim().slice(1, -1);
49
+ }
50
+
51
+ function getContributorsPage(githubUrl, optionalPrivateToken) {
52
+ return fetch(githubUrl, {
53
+ headers: getFetchHeaders(optionalPrivateToken),
54
+ }).then((res) => {
55
+ if (res.status === 404 || res.status >= 500) {
56
+ throw new Error('No contributors found on the GitHub repository');
57
+ }
58
+
59
+ return res.json().then((body) => {
60
+ if (res.status >= 400 || !res.ok) {
61
+ throw new Error(body.message);
62
+ }
63
+ const contributorsIds = body.map((contributor) => contributor.login);
64
+
65
+ const nextLink = getNextLink(res.headers.get('link'));
66
+ if (nextLink) {
67
+ return getContributorsPage(nextLink, optionalPrivateToken).then((nextContributors) => {
68
+ return contributorsIds.concat(nextContributors);
69
+ });
70
+ }
71
+
72
+ return contributorsIds;
73
+ });
74
+ });
75
+ }
76
+
77
+ export const getUserInfo = function (username, hostname, optionalPrivateToken) {
78
+ if (!username) {
79
+ throw new Error(`No login when adding a contributor. Please specify a username.`);
80
+ }
81
+
82
+ const root = getApiHost(hostname);
83
+ return fetch(`${root}/users/${username}`, {
84
+ headers: getFetchHeaders(optionalPrivateToken),
85
+ }).then((res) =>
86
+ res.json().then((body) => {
87
+ let profile = isValidHttpUrl(body.blog) ? body.blog : body.html_url;
88
+
89
+ // Check for authentication required
90
+ if ((!profile && body.message.includes('Must authenticate')) || res.status === 401) {
91
+ throw new Error(`Missing authentication for GitHub API. Did you set PRIVATE_TOKEN?`);
92
+ }
93
+
94
+ // Github throwing specific errors as 200...
95
+ if (!profile && body.message) {
96
+ if (body.message.toLowerCase().includes('api rate limit exceeded')) {
97
+ throw new Error(body.message);
98
+ } else {
99
+ throw new Error(`The username ${username} doesn't exist on GitHub.`);
100
+ }
101
+ }
102
+
103
+ profile = parseHttpUrl(profile);
104
+
105
+ return {
106
+ login: body.login,
107
+ name: body.name || username,
108
+ avatar_url: body.avatar_url,
109
+ profile,
110
+ };
111
+ }),
112
+ );
113
+ };
114
+
115
+ export const getContributors = function (owner, name, hostname, optionalPrivateToken) {
116
+ const root = getApiHost(hostname);
117
+ const contributorsUrl = `${root}/repos/${owner}/${name}/contributors?per_page=100`;
118
+ return getContributorsPage(contributorsUrl, optionalPrivateToken);
119
+ };
@@ -0,0 +1,91 @@
1
+ import { isValidHttpUrl } from '../util/url.js';
2
+
3
+ const addPrivateToken = (url, privateToken = '') => {
4
+ if (privateToken === '') return url;
5
+
6
+ return `${url}&private_token=${privateToken}`.replace(/\?/g, '&').replace('&', '?');
7
+ };
8
+
9
+ const getUserInfo = function (username, hostname, privateToken) {
10
+ if (!hostname) {
11
+ hostname = 'https://gitlab.com';
12
+ } else if (!isValidHttpUrl(hostname)) {
13
+ throw new Error(`Invalid GitLab hostname: ${hostname}`);
14
+ }
15
+
16
+ return fetch(addPrivateToken(`${hostname}/api/v4/users?username=${username}`, privateToken), {
17
+ headers: {
18
+ 'User-Agent': 'node-fetch',
19
+ },
20
+ }).then((res) =>
21
+ res.json().then((body) => {
22
+ // Gitlab returns an array of users. If it is empty, it means the username provided does not exist
23
+ if (!body || body.length === 0) {
24
+ throw new Error(`User ${username} not found`);
25
+ }
26
+
27
+ // no private token present
28
+ if (body.message) {
29
+ throw new Error(body.message);
30
+ }
31
+
32
+ const user = body[0];
33
+
34
+ return {
35
+ login: user.username,
36
+ name: user.name || username,
37
+ avatar_url: user.avatar_url,
38
+ profile: user.web_url.startsWith('http') ? user.web_url : `http://${user.web_url}`,
39
+ };
40
+ }),
41
+ );
42
+ };
43
+
44
+ const getContributors = function (owner, name, hostname, privateToken) {
45
+ if (!hostname) {
46
+ hostname = 'https://gitlab.com';
47
+ }
48
+
49
+ return fetch(addPrivateToken(`${hostname}/api/v4/projects?search=${name}`, privateToken), {
50
+ headers: { 'User-Agent': 'node-fetch' },
51
+ }).then((res) =>
52
+ res.json().then((projects) => {
53
+ // Gitlab returns an array of users. If it is empty, it means the username provided does not exist
54
+ if (!projects || projects.length === 0) {
55
+ throw new Error(`Project ${owner}/${name} not found`);
56
+ }
57
+
58
+ let project = null;
59
+ for (let i = 0; i < projects.length; i++) {
60
+ if (projects[i].path_with_namespace === `${owner}/${name}`) {
61
+ project = projects[i];
62
+ break;
63
+ }
64
+ }
65
+
66
+ if (!project) {
67
+ throw new Error(`Project ${owner}/${name} not found`);
68
+ }
69
+
70
+ return fetch(
71
+ addPrivateToken(
72
+ `${hostname}/api/v4/projects/${project.id}/repository/contributors`,
73
+ privateToken,
74
+ ),
75
+ { headers: { 'User-Agent': 'node-fetch' } },
76
+ ).then((newRes) => {
77
+ if (newRes.status === 404 || newRes.status >= 500) {
78
+ throw new Error('No contributors found on the GitLab repository');
79
+ }
80
+ return newRes.json().then((contributors) => {
81
+ if (newRes.status >= 400 || !newRes.ok) {
82
+ throw new Error(contributors.message);
83
+ }
84
+ return contributors.map((item) => item.name);
85
+ });
86
+ });
87
+ }),
88
+ );
89
+ };
90
+
91
+ export { getContributors, getUserInfo };
@@ -0,0 +1,113 @@
1
+ import * as githubAPI from './github.js';
2
+ import * as gitlabAPI from './gitlab.js';
3
+
4
+ const privateToken =
5
+ (process.env && (process.env.ALL_CONTRIBUTORS_PRIVATE_TOKEN || process.env.PRIVATE_TOKEN)) || '';
6
+ const SUPPORTED_REPO_TYPES = {
7
+ github: {
8
+ value: 'github',
9
+ name: 'GitHub',
10
+ checkKey: 'login',
11
+ defaultHost: 'https://github.com',
12
+ linkToCommits:
13
+ '<%= options.repoHost || "https://github.com" %>/<%= options.projectOwner %>/<%= options.projectName %>/commits?author=<%= contributor.login %>',
14
+ linkToIssues:
15
+ '<%= options.repoHost || "https://github.com" %>/<%= options.projectOwner %>/<%= options.projectName %>/issues?q=author%3A<%= contributor.login %>',
16
+ linkToReviews:
17
+ '<%= options.repoHost || "https://github.com" %>/<%= options.projectOwner %>/<%= options.projectName %>/pulls?q=is%3Apr+reviewed-by%3A<%= contributor.login %>',
18
+ getUserInfo: githubAPI.getUserInfo,
19
+ getContributors: githubAPI.getContributors,
20
+ },
21
+ gitlab: {
22
+ value: 'gitlab',
23
+ name: 'GitLab',
24
+ checkKey: 'name',
25
+ defaultHost: 'https://gitlab.com',
26
+ linkToCommits:
27
+ '<%= options.repoHost || "https://gitlab.com" %>/<%= options.projectOwner %>/<%= options.projectName %>/commits/master',
28
+ linkToIssues:
29
+ '<%= options.repoHost || "https://gitlab.com" %>/<%= options.projectOwner %>/<%= options.projectName %>/issues?author_username=<%= contributor.login %>',
30
+ linkToReviews:
31
+ '<%= options.repoHost || "https://gitlab.com" %>/<%= options.projectOwner %>/<%= options.projectName %>/merge_requests?scope=all&state=all&approver_usernames[]=<%= contributor.login %>',
32
+ getUserInfo: gitlabAPI.getUserInfo,
33
+ getContributors: gitlabAPI.getContributors,
34
+ },
35
+ };
36
+
37
+ export const getChoices = function () {
38
+ return Object.keys(SUPPORTED_REPO_TYPES)
39
+ .map((key) => SUPPORTED_REPO_TYPES[key])
40
+ .map((item) => {
41
+ return {
42
+ value: item.value,
43
+ name: item.name,
44
+ };
45
+ });
46
+ };
47
+
48
+ export const getHostname = function (repoType, repoHost) {
49
+ if (repoHost) {
50
+ return repoHost;
51
+ } else if (repoType in SUPPORTED_REPO_TYPES) {
52
+ return SUPPORTED_REPO_TYPES[repoType].defaultHost;
53
+ }
54
+ return null;
55
+ };
56
+
57
+ export const getCheckKey = function (repoType) {
58
+ if (repoType in SUPPORTED_REPO_TYPES) {
59
+ return SUPPORTED_REPO_TYPES[repoType].checkKey;
60
+ }
61
+ return null;
62
+ };
63
+
64
+ export const getTypeName = function (repoType) {
65
+ if (repoType in SUPPORTED_REPO_TYPES) {
66
+ return SUPPORTED_REPO_TYPES[repoType].name;
67
+ }
68
+ return null;
69
+ };
70
+
71
+ export const getLinkToCommits = function (repoType) {
72
+ if (repoType in SUPPORTED_REPO_TYPES) {
73
+ return SUPPORTED_REPO_TYPES[repoType].linkToCommits;
74
+ }
75
+ return null;
76
+ };
77
+
78
+ export const getLinkToIssues = function (repoType) {
79
+ if (repoType in SUPPORTED_REPO_TYPES) {
80
+ return SUPPORTED_REPO_TYPES[repoType].linkToIssues;
81
+ }
82
+ return null;
83
+ };
84
+
85
+ export const getLinkToReviews = function (repoType) {
86
+ if (repoType in SUPPORTED_REPO_TYPES) {
87
+ return SUPPORTED_REPO_TYPES[repoType].linkToReviews;
88
+ }
89
+ return null;
90
+ };
91
+
92
+ export const getUserInfo = function (username, repoType, repoHost) {
93
+ if (repoType in SUPPORTED_REPO_TYPES) {
94
+ return SUPPORTED_REPO_TYPES[repoType].getUserInfo(
95
+ username,
96
+ getHostname(repoType, repoHost),
97
+ privateToken,
98
+ );
99
+ }
100
+ return null;
101
+ };
102
+
103
+ export const getContributors = function (owner, name, repoType, repoHost) {
104
+ if (repoType in SUPPORTED_REPO_TYPES) {
105
+ return SUPPORTED_REPO_TYPES[repoType].getContributors(
106
+ owner,
107
+ name,
108
+ getHostname(repoType, repoHost),
109
+ privateToken,
110
+ );
111
+ }
112
+ return null;
113
+ };
@@ -0,0 +1,81 @@
1
+ import { promises as fs } from 'fs';
2
+
3
+ import jf from 'json-fixer';
4
+
5
+ import { formatConfig } from './formatting.js';
6
+ import { UserError } from './user-error.js';
7
+
8
+ export async function readConfig(configPath) {
9
+ const config = await readConfigFile(configPath);
10
+
11
+ return { repoType: 'github', commitConvention: 'angular', ...config };
12
+ }
13
+
14
+ async function readConfigFile(configPath) {
15
+ let configFileContents;
16
+ try {
17
+ configFileContents = await fs.readFile(configPath, 'utf-8');
18
+ } catch (error) {
19
+ if (error.code === 'ENOENT') {
20
+ throw new UserError(
21
+ `Configuration file not found: ${configPath}\n` +
22
+ 'Check that the path is correct, or run `all-contributors init` ' +
23
+ 'to create a new configuration file.',
24
+ { cause: error },
25
+ );
26
+ }
27
+ throw error;
28
+ }
29
+
30
+ let config;
31
+ let changed;
32
+ try {
33
+ // json-fixer prints "There's still an error!" to stderr itself before
34
+ // throwing on malformed JSON message. json-fixer has no option to turn that off.
35
+ // we could do something hacky to silence this in the future
36
+ ({ data: config, changed } = jf(configFileContents));
37
+ } catch (error) {
38
+ throw new UserError(
39
+ `Configuration file has malformed JSON: ${configPath}\n${error.message}\n` +
40
+ 'Fix the JSON in this file, or delete it and run `all-contributors init`.',
41
+ { cause: error },
42
+ );
43
+ }
44
+
45
+ if (changed) {
46
+ const formatterConfig = await formatConfig(configPath, config);
47
+ //Updates the file with fixes
48
+ await fs.writeFile(configPath, formatterConfig);
49
+ }
50
+
51
+ return config;
52
+ }
53
+
54
+ export async function writeConfig(configPath, content) {
55
+ if (!content.projectOwner) {
56
+ throw new Error(`Error! Project owner is not set in ${configPath}`);
57
+ }
58
+
59
+ if (!content.projectName) {
60
+ throw new Error(`Error! Project name is not set in ${configPath}`);
61
+ }
62
+
63
+ if (content.files && !content.files.length) {
64
+ throw new Error(`Error! Project files was overridden and is empty in ${configPath}`);
65
+ }
66
+
67
+ return fs.writeFile(configPath, `${await formatConfig(configPath, content)}\n`);
68
+ }
69
+
70
+ export async function writeContributors(configPath, contributors) {
71
+ let config;
72
+
73
+ try {
74
+ config = await readConfigFile(configPath);
75
+ } catch (error) {
76
+ return Promise.reject(error);
77
+ }
78
+ const content = { ...config, contributors };
79
+
80
+ return writeConfig(configPath, content);
81
+ }
@@ -0,0 +1,147 @@
1
+ import * as repo from '../repo/index.js';
2
+
3
+ const defaultTypes = function (repoType) {
4
+ return {
5
+ a11y: {
6
+ symbol: '️️️️♿️',
7
+ description: 'Accessibility',
8
+ },
9
+ audio: {
10
+ symbol: '🔊',
11
+ description: 'Audio',
12
+ },
13
+ blog: {
14
+ symbol: '📝',
15
+ description: 'Blogposts',
16
+ },
17
+ bug: {
18
+ symbol: '🐛',
19
+ description: 'Bug reports',
20
+ link: repo.getLinkToIssues(repoType),
21
+ },
22
+ business: {
23
+ symbol: '💼',
24
+ description: 'Business development',
25
+ },
26
+ code: {
27
+ symbol: '💻',
28
+ description: 'Code',
29
+ link: repo.getLinkToCommits(repoType),
30
+ },
31
+ content: {
32
+ symbol: '🖋',
33
+ description: 'Content',
34
+ },
35
+ data: {
36
+ symbol: '🔣',
37
+ description: 'Data',
38
+ },
39
+ design: {
40
+ symbol: '🎨',
41
+ description: 'Design',
42
+ },
43
+ doc: {
44
+ symbol: '📖',
45
+ description: 'Documentation',
46
+ link: repo.getLinkToCommits(repoType),
47
+ },
48
+ eventOrganizing: {
49
+ symbol: '📋',
50
+ description: 'Event Organizing',
51
+ },
52
+ example: {
53
+ symbol: '💡',
54
+ description: 'Examples',
55
+ },
56
+ financial: {
57
+ symbol: '💵',
58
+ description: 'Financial',
59
+ },
60
+ fundingFinding: {
61
+ symbol: '🔍',
62
+ description: 'Funding Finding',
63
+ },
64
+ ideas: {
65
+ symbol: '🤔',
66
+ description: 'Ideas, Planning, & Feedback',
67
+ },
68
+ infra: {
69
+ symbol: '🚇',
70
+ description: 'Infrastructure (Hosting, Build-Tools, etc)',
71
+ },
72
+ maintenance: {
73
+ symbol: '🚧',
74
+ description: 'Maintenance',
75
+ },
76
+ mentoring: {
77
+ symbol: '🧑‍🏫',
78
+ description: 'Mentoring',
79
+ },
80
+ platform: {
81
+ symbol: '📦',
82
+ description: 'Packaging/porting to new platform',
83
+ },
84
+ plugin: {
85
+ symbol: '🔌',
86
+ description: 'Plugin/utility libraries',
87
+ },
88
+ projectManagement: {
89
+ symbol: '📆',
90
+ description: 'Project Management',
91
+ },
92
+ question: {
93
+ symbol: '💬',
94
+ description: 'Answering Questions',
95
+ },
96
+ research: {
97
+ symbol: '🔬',
98
+ description: 'Research',
99
+ },
100
+ review: {
101
+ symbol: '👀',
102
+ description: 'Reviewed Pull Requests',
103
+ link: repo.getLinkToReviews(repoType),
104
+ },
105
+ security: {
106
+ symbol: '🛡️',
107
+ description: 'Security',
108
+ },
109
+ talk: {
110
+ symbol: '📢',
111
+ description: 'Talks',
112
+ },
113
+ test: {
114
+ symbol: '⚠️',
115
+ description: 'Tests',
116
+ link: repo.getLinkToCommits(repoType),
117
+ },
118
+ tool: {
119
+ symbol: '🔧',
120
+ description: 'Tools',
121
+ },
122
+ translation: {
123
+ symbol: '🌍',
124
+ description: 'Translation',
125
+ },
126
+ tutorial: {
127
+ symbol: '✅',
128
+ description: 'Tutorials',
129
+ },
130
+ userTesting: {
131
+ symbol: '📓',
132
+ description: 'User Testing',
133
+ },
134
+ video: {
135
+ symbol: '📹',
136
+ description: 'Videos',
137
+ },
138
+ promotion: {
139
+ symbol: '📣',
140
+ description: 'Promotion',
141
+ },
142
+ };
143
+ };
144
+
145
+ export function contributionTypes(options) {
146
+ return { ...defaultTypes(options.repoType), ...options.types };
147
+ }
@@ -0,0 +1,24 @@
1
+ import prettier from 'prettier';
2
+
3
+ export async function formatConfig(configPath, content) {
4
+ const stringified = JSON.stringify(content, null, 2);
5
+
6
+ try {
7
+ const prettierConfig = await prettier.resolveConfig(configPath, {
8
+ useCache: false,
9
+ });
10
+
11
+ if (!prettierConfig) return stringified;
12
+
13
+ const formattedOutput = await prettier.format(stringified, {
14
+ ...prettierConfig,
15
+ parser: 'json',
16
+ });
17
+
18
+ return formattedOutput.trimEnd();
19
+ } catch {
20
+ // If Prettier can't be required or throws in general,
21
+ // assume it's not usable and we should fall back to JSON.stringify
22
+ return stringified;
23
+ }
24
+ }