Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ GitHub Enterprise is also supported by [authorizing your own domain in the optio
- [Adds search filter for 'Everything commented by you'](https://cloud.githubusercontent.com/assets/940070/25518367/cb917d3e-2c36-11e7-8475-c4e6dbe0ed6c.png)
- [Moves destructive buttons ("Close issue", "Cancel") in commenting forms away from primary button](#comment-box)
- [Adds `Yours` button to Issues/Pull Requests page](https://cloud.githubusercontent.com/assets/1282980/14636384/0d8770e4-0623-11e6-8520-2054bece2771.png)
- [Condenses long URLs into references like _user/repo/.file@`d71718d`_](https://user-images.githubusercontent.com/1402241/27252232-8fdf8ed0-538b-11e7-8f19-12d317c9cd32.png)
- Easier copy-pasting from diffs by making +/- signs unselectable
- Shows the reactions popover on hover instead of click
- Supports indenting with the tab key in textareas like the comment box (<kbd>Shift</kbd> <kbd>Tab</kbd> for original behavior)
Expand Down
2 changes: 2 additions & 0 deletions src/content.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import showRealNames from './libs/show-names';
import filePathCopyBtnListner from './libs/copy-file-path';
import addFileCopyButton from './libs/copy-file';
import linkifyCode, {editTextNodes} from './libs/linkify-urls-in-code';
import shortenLinks from './libs/shorten-links';
import * as icons from './libs/icons';
import * as pageDetect from './libs/page-detect';

Expand Down Expand Up @@ -552,6 +553,7 @@ function init() {
addCompareTab();
removeProjectsTab();
addTitleToEmojis();
shortenLinks();

diffFileHeader.destroy();
enableCopyOnY.destroy();
Expand Down
178 changes: 178 additions & 0 deletions src/libs/shorten-links.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
import select from 'select-dom';
import {getRepoURL} from './page-detect';

const patchDiffRegex = /[.](patch|diff)$/;
const releaseRegex = /releases[/]tag[/]([^/]+)/;
const labelRegex = /labels[/]([^/]+)/;
const releaseArchiveRegex = /archive[/](.+)([.]zip|[.]tar[.]gz)/;
const releaseDownloadRegex = /releases[/]download[/]([^/]+)[/](.+)/;

const reservedPaths = [
'join',
'site',
'blog',
'about',
'login',
'pulls',
'search',
'issues',
'explore',
'contact',
'pricing',
'trending',
'settings',
'features',
'business',
'personal',
'security',
'dashboard',
'showcases',
'open-source',
'marketplace'
];

const styleRevision = revision => {
if (!revision) {
return;
}
revision = revision.replace(patchDiffRegex, '');
if (/^[0-9a-f]{40}$/.test(revision)) {
revision = revision.substr(0, 7);
}
return `<code>${revision}</code>`;
};

// Filter out null values
const joinValues = (array, delimiter = '/') => {
return array.filter(s => s).join(delimiter);
};

export function shortenUrl(href) {
/**
* Parse URL
*/
const {
origin,
pathname,
search,
hash
} = new URL(href);

const isRaw = [
'https://raw.githubusercontent.com',
'https://cdn.rawgit.com',
'https://rawgit.com'
].includes(origin);

let [
user,
repo,
type,
revision,
...filePath
] = pathname.substr(1).split('/');

if (isRaw) {
[
user,
repo,
// Raw URLs don't have `blob` here
revision,
...filePath
] = pathname.substr(1).split('/');
type = 'raw';
}

revision = styleRevision(revision);
filePath = filePath.join('/');

const isLocal = origin === location.origin;
const isThisRepo = (isLocal || isRaw) && getRepoURL() === `${user}/${repo}`;
const isReserved = reservedPaths.includes(user);
const [, diffOrPatch] = pathname.match(patchDiffRegex) || [];
const [, release] = pathname.match(releaseRegex) || [];
const [, releaseTag, releaseTagExt] = pathname.match(releaseArchiveRegex) || [];
const [, downloadTag, downloadFilename] = pathname.match(releaseDownloadRegex) || [];
const [, label] = pathname.match(labelRegex) || [];
const isFileOrDir = revision && [
'raw',
'tree',
'blob',
'blame',
'commits'
].includes(type);

const repoUrl = isThisRepo ? '' : `${user}/${repo}`;

/**
* Shorten URL
*/

if (isReserved || (!isLocal && !isRaw)) {
return href
.replace(/^https:[/][/]/, '')
.replace(/^www[.]/, '')
.replace(/[/]$/, '');
}

if (user && !repo) {
return `@${user}${search}${hash}`;
}

if (isFileOrDir) {
const file = `${repoUrl}${filePath ? '/' + filePath : ''}`;
const revisioned = joinValues([file, revision], '@');
const partial = `${revisioned}${search}${hash}`;
if (type !== 'blob' && type !== 'tree') {
return `${partial} (${type})`;
}
return partial;
}

if (diffOrPatch) {
const partial = joinValues([repoUrl, revision], '@');
return `${partial}.${diffOrPatch}${search}${hash}`;
}

if (release) {
const partial = joinValues([repoUrl, `<code>${release}</code>`], '@');
return `${partial}${search}${hash} (release)`;
}

if (releaseTagExt) {
const partial = joinValues([repoUrl, `<code>${releaseTag}</code>`], '@');
return `${partial}${releaseTagExt}${search}${hash}`;
}

if (downloadFilename) {
const partial = joinValues([repoUrl, `<code>${downloadTag}</code>`], '@');
return `${partial} ${downloadFilename}${search}${hash} (download)`;
}

if (label) {
return joinValues([repoUrl, label]) + `${search}${hash} (label)`;
}

// Drop leading and trailing slash of relative path
return `${pathname.replace(/^[/]|[/]$/g, '')}${search}${hash}`;
}

export default () => {
for (const a of select.all('a[href]')) {
// Don't change if it was already customized
// .href automatically adds a / to naked origins
// so that needs to be tested too
if (a.href !== a.textContent && a.href !== `${a.textContent}/`) {
continue;
}

const shortened = shortenUrl(a.href);

// Don't touch the dom if there's nothing to change
if (shortened === a.textContent) {
continue;
}

a.innerHTML = shortened;
}
};
19 changes: 3 additions & 16 deletions test/fixtures/window.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,7 @@
const url = require('url');
const URL = require('url').URL;

function WindowMock(initialURI) {
this._currentURI = initialURI;
function WindowMock(initialURI = 'https://github.com') {
this.location = new URL(initialURI);
}

WindowMock.prototype.location = {
set href(uri) {
const uriParts = url.parse(uri);
this.hostname = uriParts.hostname;
this.pathname = uriParts.pathname;
this._currentURI = uri;
},

get href() {
return this._currentURI;
}
};

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

module.exports = WindowMock;
Loading