Merge pull request #666 from chen-chao/localhost

support url started with localhost
jh-changes
Shin'ya Ueoka 5 years ago committed by GitHub
commit ae77b386f4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 27
      src/shared/urls.ts
  2. 16
      test/shared/urls.test.ts

@ -7,6 +7,29 @@ const trimStart = (str: string): string => {
const SUPPORTED_PROTOCOLS = ['http:', 'https:', 'ftp:', 'mailto:', 'about:']; const SUPPORTED_PROTOCOLS = ['http:', 'https:', 'ftp:', 'mailto:', 'about:'];
const isLocalhost = (url: string): boolean => {
if (url === 'localhost') {
return true;
}
let [host, port] = url.split(':', 2);
return host === 'localhost' && !isNaN(Number(port));
};
const isMissingHttp = (keywords: string): boolean => {
if (keywords.includes('.') && !keywords.includes(' ')) {
return true;
}
try {
let u = new URL('http://' + keywords);
return isLocalhost(u.host)
} catch (e) {
// fallthrough
}
return false;
};
const searchUrl = (keywords: string, search: Search): string => { const searchUrl = (keywords: string, search: Search): string => {
try { try {
let u = new URL(keywords); let u = new URL(keywords);
@ -16,9 +39,11 @@ const searchUrl = (keywords: string, search: Search): string => {
} catch (e) { } catch (e) {
// fallthrough // fallthrough
} }
if (keywords.includes('.') && !keywords.includes(' ')) {
if (isMissingHttp(keywords)) {
return 'http://' + keywords; return 'http://' + keywords;
} }
let template = search.engines[search.defaultEngine]; let template = search.engines[search.defaultEngine];
let query = keywords; let query = keywords;

@ -36,6 +36,21 @@ describe("shared/commands/parsers", () => {
expect(parsers.searchUrl('std::vector', config)) expect(parsers.searchUrl('std::vector', config))
.to.equal('https://google.com/search?q=std%3A%3Avector'); .to.equal('https://google.com/search?q=std%3A%3Avector');
}); });
it('localhost urls', () => {
expect(parsers.searchUrl('localhost', config))
.to.equal('http://localhost');
expect(parsers.searchUrl('http://localhost', config))
.to.equal('http://localhost/');
expect(parsers.searchUrl('localhost:8080', config))
.to.equal('http://localhost:8080');
expect(parsers.searchUrl('localhost:80nan', config))
.to.equal('https://google.com/search?q=localhost%3A80nan');
expect(parsers.searchUrl('localhost 8080', config))
.to.equal('https://google.com/search?q=localhost%208080');
expect(parsers.searchUrl('localhost:80/build', config))
.to.equal('http://localhost:80/build')
})
}); });
describe('#normalizeUrl', () => { describe('#normalizeUrl', () => {
@ -47,4 +62,3 @@ describe("shared/commands/parsers", () => {
}); });
}); });
}); });