Skip to content

Commit ac5347c

Browse files
committed
Included the code on the readme
Removed unusued code
1 parent 791e763 commit ac5347c

File tree

2 files changed

+167
-61
lines changed

2 files changed

+167
-61
lines changed

README.md

+167
Original file line numberDiff line numberDiff line change
@@ -1256,3 +1256,170 @@ assert (len(node_output) > 0)
12561256
Depois de testarmos o minimo do uso da linha de comando, nós vamos dar atenção
12571257
a implementação util em outros motores de execução, neste caso nós devemos
12581258
seguir o que esta sendo levantado como exceção pelo motor, neste caso o Deno.
1259+
1260+
Para esta implementação nós vamos ter que lidar com um método chamado "traverse"
1261+
que varre os diretorios e quando encontra arquivos procura pela ocorrencia de texto
1262+
e outro comportamento util é a utilização de um código que faz a busca na entrada
1263+
de texto padrão.
1264+
1265+
```typescript
1266+
'use strict';
1267+
1268+
import { existsSync } from 'https://deno.land/std/fs/mod.ts';
1269+
1270+
function thrownArgumentException(text: string, term: string): void {
1271+
if (typeof term !== 'string' || typeof text !== 'string') {
1272+
throw new Error('Each argument, must be a string');
1273+
}
1274+
}
1275+
1276+
export function search(term: string, text: string): boolean {
1277+
thrownArgumentException(term, text);
1278+
return (new RegExp(term)).test(text);
1279+
}
1280+
1281+
export function times(term: string, text: string): number {
1282+
thrownArgumentException(term, text);
1283+
let out = 0;
1284+
let matched = text.match((new RegExp(term, 'g')));
1285+
if (matched !== null) {
1286+
out = matched.length;
1287+
}
1288+
return out;
1289+
}
1290+
1291+
export function match(term: string, text: string): string {
1292+
thrownArgumentException(term, text);
1293+
let out = '';
1294+
let matched = text.match(new RegExp(term));
1295+
if (matched !== null && matched.input !== undefined) {
1296+
out = matched.input;
1297+
}
1298+
return out;
1299+
}
1300+
1301+
export class TextContent {
1302+
content: any;
1303+
1304+
constructor(content: any) {
1305+
this.content = content;
1306+
this.setContent = this.setContent.bind(this);
1307+
this.getContent = this.getContent.bind(this);
1308+
this.isBuffer = this.isBuffer.bind(this);
1309+
this.search = this.search.bind(this);
1310+
this.times = this.times.bind(this);
1311+
this.match = this.match.bind(this);
1312+
}
1313+
1314+
setContent(value: any) {
1315+
this.content = value;
1316+
return this;
1317+
}
1318+
1319+
getContent() {
1320+
return this.content;
1321+
}
1322+
1323+
isBuffer(value: Deno.Buffer) {
1324+
return value.constructor.toString().indexOf('Buffer') > -1;
1325+
}
1326+
1327+
search(term: any) {
1328+
if (this.isBuffer(term) && this.isBuffer(this.getContent())) {
1329+
return this.getContent().indexOf(term) > -1;
1330+
}
1331+
return search(term, this.getContent());
1332+
}
1333+
1334+
times(term: any, t: number =-1, o: number = 0): any {
1335+
if (this.isBuffer(term) && this.isBuffer(this.getContent())) {
1336+
let out = o;
1337+
let curr = this.getContent().indexOf(term, t + 1);
1338+
if (curr > -1) {
1339+
out += 1;
1340+
return this.times(term, t=curr + 1, out);
1341+
}
1342+
return out;
1343+
}
1344+
return times(term, this.getContent());
1345+
}
1346+
1347+
match(term: any): any {
1348+
if (this.isBuffer(term) && this.isBuffer(this.getContent())) {
1349+
let out: { [k: string]: any } = {};
1350+
let lines = [];
1351+
let line = [];
1352+
for (let i = 0; i < this.getContent().length; i += 1) {
1353+
let chr = this.getContent()[i];
1354+
if (chr === '\n'.charCodeAt(0)) {
1355+
lines.push(line);
1356+
line = [];
1357+
} else if (i === this.getContent().length - 1) {
1358+
line.push(chr);
1359+
lines.push(line);
1360+
line = [];
1361+
} else {
1362+
line.push(chr);
1363+
}
1364+
}
1365+
for (let i in lines) {
1366+
let curr = lines[i];
1367+
if (curr.indexOf(term) > -1) {
1368+
out[(parseInt(i, 10) + 1)] = curr;
1369+
}
1370+
}
1371+
return out;
1372+
}
1373+
return match(term, this.getContent());
1374+
}
1375+
}
1376+
1377+
export class Lines {}
1378+
1379+
async function traverse(dir=Deno.cwd()) {
1380+
if (Deno.cwd() !== dir) {
1381+
dir = Deno.cwd() + '/' + dir;
1382+
} if (existsSync(dir)) {
1383+
for await (const dirEntry of Deno.readDir(dir)) {
1384+
if (dirEntry.isFile) {
1385+
let decoder = new TextDecoder('utf-8');
1386+
let rawPath = Deno.cwd() + '/' + dirEntry.name;
1387+
if (existsSync(rawPath)) {
1388+
let raw = await Deno.readFile(rawPath);
1389+
let data = decoder.decode(raw);
1390+
let text = new TextContent(data.toString());
1391+
if (text.search(Deno.args[0])) {
1392+
let matches = text.match(Deno.args[0]);
1393+
let output = matches.replace((new RegExp(Deno.args[0], 'g')), '\x1b[100m' + Deno.args[0] + '\x1b[49m');
1394+
console.log(`${output}`);
1395+
}
1396+
}
1397+
} else if (dirEntry.isDirectory) {
1398+
traverse(dirEntry.name);
1399+
}
1400+
}
1401+
}
1402+
}
1403+
1404+
if (!!Deno.args.length && Deno.isatty(Deno.stdin.rid)) {
1405+
traverse();
1406+
} else if (!!Deno.args.length && !Deno.isatty(Deno.stdin.rid)) {
1407+
(async () => {
1408+
let decoder = new TextDecoder('utf-8');
1409+
let raw = await Deno.readAll(Deno.stdin);
1410+
let data = decoder.decode(raw);
1411+
let text = new TextContent(data.toString());
1412+
if (text.search(Deno.args[0])) {
1413+
let matches = text.match(Deno.args[0]);
1414+
let output = matches.replace((new RegExp(Deno.args[0], 'g')), '\x1b[100m' + Deno.args[0] + '\x1b[49m');
1415+
console.log(`${output}`);
1416+
}
1417+
})();
1418+
}
1419+
```
1420+
1421+
Com isto nós podemos verificar que a implementação contou também com uma verificação
1422+
se a entrada era do tipo "tty" para se comportar da maneira adequada. Ao executar
1423+
este código você vai encontrar o necessário para saber o que fazer após. E esta
1424+
é a nossa finalização do programa, e podemos melhorar muito mais este programa.
1425+
Vamos para a parte de analise e refatoração.

main.ts

-61
Original file line numberDiff line numberDiff line change
@@ -151,64 +151,3 @@ if (!!Deno.args.length && Deno.isatty(Deno.stdin.rid)) {
151151
}
152152
})();
153153
}
154-
155-
// const isTTY = process.stdin.isTTY;
156-
// const { Transform } = require('stream');
157-
// const args = process.argv.slice(2);
158-
//
159-
// function textMatchContentTransformFactory(filePath='') {
160-
// const opts = {
161-
// transform(raw, encoding, callback) {
162-
// let text = new TextContent(raw);
163-
// if (!!args.length && text.search(new Deno.Buffer(args[0]))) {
164-
// if (!!filePath) console.log(filePath);
165-
// let matches = text.match(new Deno.Buffer(args[0]));
166-
// let lines = [];
167-
// Object.keys(matches).forEach(k => {
168-
// lines.push(`${k}:${matches[k].toString().replace((new RegExp(args[0], 'g')), '\x1b[100m' + args[0] + '\x1b[49m')}`);
169-
// });
170-
// this.push(new Deno.Buffer(`${lines.join('\n')}\n`));
171-
// }
172-
// callback();
173-
// }
174-
// };
175-
// return new Transform(opts);
176-
// }
177-
//
178-
// const fs = require('fs');
179-
// const path = require('path');
180-
//
181-
// function traverse(dirPath, dirs=[]) {
182-
// let dir = fs.readdirSync(dirPath, {
183-
// withFileTypes: true
184-
// });
185-
// let nestedDirs = dir.filter(curr => curr.isDirectory() &&
186-
// !(curr.name.indexOf('.') === 0));
187-
// let nestedFiles = dir.filter(curr => curr.isFile() &&
188-
// !(curr.name.indexOf('.') === 0));
189-
//
190-
// for (let file of nestedFiles) {
191-
// let curr = path.resolve(dirPath, file.name);
192-
// let currStream = fs.createReadStream(curr);
193-
//
194-
// currStream.setMaxListeners(100000);
195-
//
196-
// currStream.pipe(textMatchContentTransformFactory(curr)).pipe(process.stdout);
197-
// }
198-
//
199-
// for (let entrypoint of nestedDirs) {
200-
// let curr = path.resolve(dirPath, entrypoint.name);
201-
// traverse(curr);
202-
// }
203-
// }
204-
//
205-
// process.stdin.setEncoding('utf-8');
206-
//
207-
// process.stdout.setMaxListeners(100000);
208-
//
209-
// if (!isTTY) {
210-
// process.stdin.pipe(textMatchContentTransformFactory()).pipe(process.stdout);
211-
// } else if (isTTY && !module.parent) {
212-
// // traverse directories
213-
// traverse(process.cwd());
214-
// }

0 commit comments

Comments
 (0)