forked from Laboratoria/SAP009-md-links
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
147 lines (131 loc) · 4.61 KB
/
cli.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#!/usr/bin/env node
const chalk = require('chalk');
const mdLinks = require('./mdLink');
//Process. argv: A process.argv propriedade retorna uma matriz contendo os argumentos de linha de comando passados quando o processo Node.js foi iniciado
const pathFile = process.argv[2];
const options = process.argv[3];
const statusDaMensagem = {
'200': 'OK',
'201': 'Criado',
'204': 'Nenhum conteúdo',
'400': 'Requisição inválida',
'401': 'Não autorizado',
'403': 'Proibido',
'404': 'Não encontrado',
'500': 'Erro interno do servidor',
'502': 'Gateway ruim',
'503': 'Serviço indisponível',
};
function buscarLink(element) {
if (!element || !element.href) {
return Promise.reject(new Error(`O elemento é invalido ou está sem URL`));
}
//esta chamando a função fetch
return fetch(element.href)
.then(response => {
element.status = response.status;
//esta pegando a resposta do status e estra tranformando em uma string
element.statusText = statusDaMensagem[response.status.toString()] || response.statusText;
return element;
})
.catch(error => {
element.status = 'Elemento não encontrado';
element.statusText = error.message;
return element;
});
};
function imprimirEstatistica(result) {
const verificaLink = [...new Set(result.map(element => element.href))];
const recebeEstatistica = {
total: result.length,
unique: verificaLink.length,
};
console.log(chalk.yellow('\u2666') + ' ' + chalk.yellow('Total:'), chalk.green(recebeEstatistica.total));
console.log(chalk.yellow('\u2666') + ' ' + chalk.yellow('Unique:'), chalk.green(recebeEstatistica.unique));
};
function imprimeResultadoValidacao(element) {
const statusColor = element.status >= 200 && element.status < 300 ? chalk.green : chalk.red.bold;
console.log(
statusColor('\u2705'),
chalk.green(element.file),
chalk.white(element.href),
statusColor(`${element.status} ${element.statusText}`),
chalk.green(element.text)
);
};
function imprimirEstatisticaComFalha(result) {
const promises = result.map(element => buscarLink(element));
Promise.all(promises)
.then(linksArray => {
const verificaLink = [...new Set(linksArray.map(element => element.href))];
const recebeEstatistica = {
total: linksArray.length,
unique: verificaLink.length,
broken: linksArray.filter(element => element.status !== 200).length,
};
console.log(chalk.yellow('\u2666') + ' ' + chalk.yellow('Total:'), chalk.green(recebeEstatistica.total));
console.log(chalk.yellow('\u2666') + ' ' + chalk.yellow('Unique:'), chalk.green(recebeEstatistica.unique));
console.log(chalk.red('\u203C') + ' ' + chalk.red('Broken:'), chalk.red.bold(recebeEstatistica.broken));
})
.catch(error => {
console.error(error);
});
};
function estatisticasComOpcaoDeValidacao() {
mdLinks(pathFile)
.then(result => {
imprimirEstatisticaComFalha(result);
})
.catch(error => {
console.log('Erro');
console.error(error);
});
};
function manipularOpcaoValidada() {
mdLinks(pathFile)
.then(result => {
const promises = result.map(element => buscarLink(element));
Promise.all(promises)
.then(linksArray => {
linksArray.forEach(element => {
imprimeResultadoValidacao(element);
});
})
.catch(error => {
console.error(error);
});
})
.catch(error => {
console.log('Error');
console.error(error);
})
};
function manipularOpcaoEstatisca() {
mdLinks(pathFile)
.then(result => {
imprimirEstatistica(result);
})
.catch(error => {
console.log('Erro');
console.error(error);
});
};
if(options === '--stats' && process.argv.includes('--validate')) {
estatisticasComOpcaoDeValidacao();
} else if(options === '--validate') {
manipularOpcaoValidada();
} else if(options === '--stats') {
manipularOpcaoEstatisca();
//manipulação sem opção selecionada
} else {
mdLinks(pathFile)
.then(result => {
result.forEach(element => {
console.log(chalk.magenta('\u2605') + ' ' + chalk.magenta(element.file), chalk.yellow(element.href), chalk.blue('\u27A4') + ' ' + ' ' + chalk.gray(element.text));
});
})
.catch(error => {
console.log('Error');
console.error(error);
});
}