code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function scroll(e) { e = e || window.event; stopBubble(e); stopDefault(e); var window_top = $window.scrollTop(); var delta = -e.wheelDelta / 120 || e.detail / 3; var move = delta * options.steps; slide(window_top + move); $document.scrollTop(window_top + move); }
jquery.scrolldiv.js 1.0 http://jquerywidget.com
scroll
javascript
mumuy/widget
code/jquery.scrolldiv.js
https://github.com/mumuy/widget/blob/master/code/jquery.scrolldiv.js
MIT
function slide(top){ var top = top || $document.scrollTop(); var scroll_height = top - _position_top; var distance = _maxheight-_window_height; if (scroll_height < 0) { $list.css("top", "0px"); } else if(scroll_height>distance) { $list.each(function(i){ $list.eq(i).css("top",_maxheight-$list.eq(i).height()+'px'); }); }else{ var times = scroll_height /distance; $list.each(function(i){ $list.eq(i).css("top",(_maxheight - $list.eq(i).height()) * times + "px"); }); } }
jquery.scrolldiv.js 1.0 http://jquerywidget.com
slide
javascript
mumuy/widget
code/jquery.scrolldiv.js
https://github.com/mumuy/widget/blob/master/code/jquery.scrolldiv.js
MIT
function stopBubble(e) { if (e && e.stopPropagation) { e.stopPropagation(); } else if (window.event) { window.event.cancelBubble = true; } }
jquery.scrolldiv.js 1.0 http://jquerywidget.com
stopBubble
javascript
mumuy/widget
code/jquery.scrolldiv.js
https://github.com/mumuy/widget/blob/master/code/jquery.scrolldiv.js
MIT
function stopDefault(e) { if (e && e.preventDefault) { e.preventDefault(); } else { window.event.returnValue = false; } return false; }
jquery.scrolldiv.js 1.0 http://jquerywidget.com
stopDefault
javascript
mumuy/widget
code/jquery.scrolldiv.js
https://github.com/mumuy/widget/blob/master/code/jquery.scrolldiv.js
MIT
down = function(e){ if(isShow){ e.isPropagationStopped(); switch(e.keyCode){ case 13: _api.setValue($options.eq(_index).val()); isShow = false; break; case 38: if(_index>0){ _index--; $items.eq(_index).addClass(options.prefix+'-active').siblings().removeClass(options.prefix+'-active'); } e.preventDefault(); break; case 40: if(_index<$items.length-1){ _index++; $items.eq(_index).addClass(options.prefix+'-active').siblings().removeClass(options.prefix+'-active'); } e.preventDefault(); break; } } }
jquery.select.js 1.2 http://jquerywidget.com
down
javascript
mumuy/widget
code/jquery.select.js
https://github.com/mumuy/widget/blob/master/code/jquery.select.js
MIT
function scroll(){ if(!isClose){ var scrolltop = $document.scrollTop(); if(scrolltop<options.scrolltop){ hide(); }else { show(); } } }
jquery.sliderbar.js 1.0 http://jquerywidget.com
scroll
javascript
mumuy/widget
code/jquery.slidebar.js
https://github.com/mumuy/widget/blob/master/code/jquery.slidebar.js
MIT
function hide(){ if(isShow){ $this.animate({'width':'0px'},options.duration); isShow = false; } }
jquery.sliderbar.js 1.0 http://jquerywidget.com
hide
javascript
mumuy/widget
code/jquery.slidebar.js
https://github.com/mumuy/widget/blob/master/code/jquery.slidebar.js
MIT
function show(){ if(!isShow){ $this.animate({'width':_width},options.duration); isShow = true; } }
jquery.sliderbar.js 1.0 http://jquerywidget.com
show
javascript
mumuy/widget
code/jquery.slidebar.js
https://github.com/mumuy/widget/blob/master/code/jquery.slidebar.js
MIT
function close(){ addCookie(options.cookieName,"1",options.expires,options.cookieDomain,options.cookiePath); hide(); isClose = true; options.afterClose(); }
jquery.sliderbar.js 1.0 http://jquerywidget.com
close
javascript
mumuy/widget
code/jquery.slidebar.js
https://github.com/mumuy/widget/blob/master/code/jquery.slidebar.js
MIT
function open(){ // delCookie(options.cookieName,options.cookieDomain,options.cookiePath); show(); isClose = false; options.afterOpen(); }
jquery.sliderbar.js 1.0 http://jquerywidget.com
open
javascript
mumuy/widget
code/jquery.slidebar.js
https://github.com/mumuy/widget/blob/master/code/jquery.slidebar.js
MIT
function delCookie(name,objDomain,objPath){ document.cookie = name+"=;expires="+(new Date(0)).toGMTString()+";domain="+objDomain+";path="+objPath; }
jquery.sliderbar.js 1.0 http://jquerywidget.com
delCookie
javascript
mumuy/widget
code/jquery.slidebar.js
https://github.com/mumuy/widget/blob/master/code/jquery.slidebar.js
MIT
function getCookie(objName){ var arrStr = document.cookie.split("; "); for(var i = 0;i < arrStr.length;i ++){ var temp = arrStr[i].split("="); if(temp[0] == objName) return unescape(temp[1]); } }
jquery.sliderbar.js 1.0 http://jquerywidget.com
getCookie
javascript
mumuy/widget
code/jquery.slidebar.js
https://github.com/mumuy/widget/blob/master/code/jquery.slidebar.js
MIT
reset = function(){ _height = $this.outerHeight(false); _width = $this.outerWidth(false); _top = $this.position().top; _left = $this.position().left; $suggestion.css({ 'top':_top+_height+'px', 'left':_left+'px', 'width':_width+'px' }); }
jquery.suggestion.js 1.5 http://jquerywidget.com
reset
javascript
mumuy/widget
code/jquery.suggestion.js
https://github.com/mumuy/widget/blob/master/code/jquery.suggestion.js
MIT
down = function(e){ e.isPropagationStopped(); switch(e.keyCode){ case 13: _api.hide(); if(_index>=0){ var $target = $items.eq(_index); var data = { 'name':$target.data('name'), 'value':$target.data('value'), }; var result = options.onSelect(data); if(result!=false){ $this.val(result); $this.data('value',data.value); } } if(!options.autoSubmit){ e.preventDefault(); } break; case 38: if(isShow){ if(_index>0){ _index--; $items.eq(_index).addClass(options.activeCls).siblings().removeClass(options.activeCls); change(); }else{ _index = -1; $items.removeClass(options.activeCls); $this.val(_text); } e.preventDefault(); } break; case 40: if(isShow){ if(_index<$items.length-1){ _index++; $items.eq(_index).addClass(options.activeCls).siblings().removeClass(options.activeCls); change(); } e.preventDefault(); } break; } }
jquery.suggestion.js 1.5 http://jquerywidget.com
down
javascript
mumuy/widget
code/jquery.suggestion.js
https://github.com/mumuy/widget/blob/master/code/jquery.suggestion.js
MIT
hover = function(e){ e.isPropagationStopped(); var $target = $(this); _index = $target.index(); $target.addClass(options.activeCls).siblings().removeClass(options.activeCls); }
jquery.suggestion.js 1.5 http://jquerywidget.com
hover
javascript
mumuy/widget
code/jquery.suggestion.js
https://github.com/mumuy/widget/blob/master/code/jquery.suggestion.js
MIT
function hasScrolled(element, direction) { if (direction === 'vertical') { return element.scrollHeight > element.clientHeight; } else if (direction === 'horizontal') { return element.scrollWidth > element.clientWidth; } }
jquery.suggestion.js 1.5 http://jquerywidget.com
hasScrolled
javascript
mumuy/widget
code/jquery.suggestion.js
https://github.com/mumuy/widget/blob/master/code/jquery.suggestion.js
MIT
change = function(){ var $target = $list.find('li.'+options.activeCls); var data = { 'name':$target.data('name'), 'value':$target.data('value'), }; var result = options.onChange.bind(_)(data); if(result!=false){ var $parent = $target.parent(); if(!hasScrolled($parent[0],'vertical')){ $parent = $parent.parent(); } var top = $target.position().top+$parent.scrollTop(); var height = $target.outerHeight(); var outer_height = $parent.outerHeight(); var scroll_top = Math.max(top-outer_height/2+height/2,0); $parent.scrollTop(scroll_top); $this.val(result); $this.data('value',data.value); } }
jquery.suggestion.js 1.5 http://jquerywidget.com
change
javascript
mumuy/widget
code/jquery.suggestion.js
https://github.com/mumuy/widget/blob/master/code/jquery.suggestion.js
MIT
reset = function(){ var border_width = parseInt($table.find('th,td').css('border-width')) + parseInt($table.css('border-spacing'))*2; var thead_height = $table.find('thead').outerHeight(true)+border_width; var thead_width = border_width; $table.find('thead').find('td,th').each(function(index){ if(index<options.fixedColumnCount){ thead_width += $(this).outerWidth(true); } }); $fixed_corner.html($table.clone()).width(thead_width).height(thead_height); $fixed_header.html($table.clone()).height(thead_height); $fixed_column.html($table.clone()).width(thead_width); }
jquery.tablefixed.js 1.0 http://jquerywidget.com
reset
javascript
mumuy/widget
code/jquery.tablefixed.js
https://github.com/mumuy/widget/blob/master/code/jquery.tablefixed.js
MIT
getOuterRange = function (range) { var getRange = function(){ $abledTds.each(function () { var $temp = $(this); var t_fromKey = $temp.data('from'); var t_toKey = $temp.data('to'); var t_from = t_fromKey.split(':').map(function (value) { return +value; }); var t_to = t_toKey.split(':').map(function (value) { return +value; }); if (isInRange({ from: t_from, to: t_to }, range)) { cellList.push({ 'from': t_from, 'to': t_to, }); } }); var outer_from = [Math.min.apply(null, cellList.map(function (item) { return Math.min(item['from'][0],item['to'][0]); })), Math.min.apply(null, cellList.map(function (item) { return Math.min(item['from'][1],item['to'][1]); }))]; var outer_to = [Math.max.apply(null, cellList.map(function (item) { return Math.max(item['from'][0],item['to'][0]); })), Math.max.apply(null, cellList.map(function (item) { return Math.max(item['from'][1],item['to'][1]); }))]; return { from: outer_from, to: outer_to }; }; var temp_range = JSON.parse(JSON.stringify(selected_range)); var outer_range = getRange(temp_range); while (outer_range['from'][0] != temp_range['from'][0] || outer_range['from'][1] != temp_range['from'][1] || outer_range['to'][0] != temp_range['to'][0] || outer_range['to'][1] != temp_range['to'][1]) { temp_range = outer_range; outer_range = getRange(outer_range); } return outer_range; }
jquery.tableselect.js 1.1 http://jquerywidget.com
getOuterRange
javascript
mumuy/widget
code/jquery.tableselect.js
https://github.com/mumuy/widget/blob/master/code/jquery.tableselect.js
MIT
getRange = function(){ $abledTds.each(function () { var $temp = $(this); var t_fromKey = $temp.data('from'); var t_toKey = $temp.data('to'); var t_from = t_fromKey.split(':').map(function (value) { return +value; }); var t_to = t_toKey.split(':').map(function (value) { return +value; }); if (isInRange({ from: t_from, to: t_to }, range)) { cellList.push({ 'from': t_from, 'to': t_to, }); } }); var outer_from = [Math.min.apply(null, cellList.map(function (item) { return Math.min(item['from'][0],item['to'][0]); })), Math.min.apply(null, cellList.map(function (item) { return Math.min(item['from'][1],item['to'][1]); }))]; var outer_to = [Math.max.apply(null, cellList.map(function (item) { return Math.max(item['from'][0],item['to'][0]); })), Math.max.apply(null, cellList.map(function (item) { return Math.max(item['from'][1],item['to'][1]); }))]; return { from: outer_from, to: outer_to }; }
jquery.tableselect.js 1.1 http://jquerywidget.com
getRange
javascript
mumuy/widget
code/jquery.tableselect.js
https://github.com/mumuy/widget/blob/master/code/jquery.tableselect.js
MIT
sortTableByIndex = function(index,type){ var type = type||'up'; var $bd_tbody = $table.find('tbody'); $bd_tbody.find('td').removeClass(options.activeCls).filter(':nth-child('+(index+1)+')').addClass(options.activeCls); var $items = $bd_tbody.find('tr'); var $temps = $items.clone(); var list = $.map($items,function(item,i){ var $item = $(item); var value = $item.find('td').eq(index).data('value')||0; return { 'index':i, 'value':value }; }); if(type=='up'){ list.sort(function(item1,item2){ if(isNaN(item1['value'])||isNaN(item2['value'])){ return item1['value'].toString().localeCompare(item2['value'].toString()); }else{ return item1['value']-item2['value']; } }); }else{ list.sort(function(item1,item2){ if(isNaN(item1['value'])||isNaN(item2['value'])){ return item2['value'].toString().localeCompare(item1['value'].toString()); }else{ return item2['value']-item1['value']; } }); } $bd_tbody.append($temps); $temps.each(function(index){ var $this = $(this); var $temp = $items.eq(list[index]['index']); $this.replaceWith($temp); }); }
jquery.tablesort.js 1.0 http://jquerywidget.com
sortTableByIndex
javascript
mumuy/widget
code/jquery.tablesort.js
https://github.com/mumuy/widget/blob/master/code/jquery.tablesort.js
MIT
prev = function(e){ var i = _index?_index-1:_size-1; var status = { index: _index, count: _size, destination: i, event:e }; if(options.onChangeStart(status)!=false){ _api.setIndex(i); options.onChangeEnd({index:i,count: _size}); } }
jquery.tabs.js 1.0 http://jquerywidget.com
prev
javascript
mumuy/widget
code/jquery.tabs.js
https://github.com/mumuy/widget/blob/master/code/jquery.tabs.js
MIT
next = function(e){ var i = (_index + 1)%_size; var status = { index: _index, count: _size, destination: i, event:e }; if(options.onChangeStart(status)!=false){ _api.setIndex(i); options.onChangeEnd({index:i,count: _size}); } }
jquery.tabs.js 1.0 http://jquerywidget.com
next
javascript
mumuy/widget
code/jquery.tabs.js
https://github.com/mumuy/widget/blob/master/code/jquery.tabs.js
MIT
down = function(e){ if(isShow){ e.isPropagationStopped(); switch(e.keyCode){ case 13: _api.value($options.eq(_index).val()); isShow = false; break; case 38: if(_index>0){ _index--; $items.eq(_index).addClass(options.activeCls).siblings().removeClass(options.activeCls); } e.preventDefault(); break; case 40: if(_index<$items.length-1){ _index++; $items.eq(_index).addClass(options.activeCls).siblings().removeClass(options.activeCls); } e.preventDefault(); break; } } }
zepto.select.js 1.0 http://jquerywidget.com
down
javascript
mumuy/widget
code/zepto.select.js
https://github.com/mumuy/widget/blob/master/code/zepto.select.js
MIT
transformVendorKeys = (manifest, vendor) => { if (Array.isArray(manifest)) { return manifest.map(newManifest => { return transformVendorKeys(newManifest, vendor); }); } if (typeof manifest === 'object') { return Object.entries(manifest).reduce((newManifest, [key, value]) => { const match = key.match(vendorRegExp); if (match) { const vendors = match[1].split('|'); // Swap key with non prefixed name if (vendors.indexOf(vendor) > -1) { newManifest[match[2]] = value; } } else { newManifest[key] = transformVendorKeys(value, vendor); } return newManifest; }, {}); } return manifest; }
Fork of `webextension-toolbox/webpack-webextension-plugin`
transformVendorKeys
javascript
ineo6/git-master
scripts/wext-manifest/transformVendorKeys.js
https://github.com/ineo6/git-master/blob/master/scripts/wext-manifest/transformVendorKeys.js
MIT
transformVendorKeys = (manifest, vendor) => { if (Array.isArray(manifest)) { return manifest.map(newManifest => { return transformVendorKeys(newManifest, vendor); }); } if (typeof manifest === 'object') { return Object.entries(manifest).reduce((newManifest, [key, value]) => { const match = key.match(vendorRegExp); if (match) { const vendors = match[1].split('|'); // Swap key with non prefixed name if (vendors.indexOf(vendor) > -1) { newManifest[match[2]] = value; } } else { newManifest[key] = transformVendorKeys(value, vendor); } return newManifest; }, {}); } return manifest; }
Fork of `webextension-toolbox/webpack-webextension-plugin`
transformVendorKeys
javascript
ineo6/git-master
scripts/wext-manifest/transformVendorKeys.js
https://github.com/ineo6/git-master/blob/master/scripts/wext-manifest/transformVendorKeys.js
MIT
async activate(opts, payload) { return undefined; }
Activates the plugin. @param {!{ adapter: !Adapter, $sidebar: !JQuery, $toggler: !JQuery, $views: !JQuery, treeView: !TreeView, optsView: !OptionsView, errorView: !ErrorView, }} @param {{ state: UserState, }} @return {!Promise<undefined>}
activate
javascript
ineo6/git-master
src/common/core.plugins.js
https://github.com/ineo6/git-master/blob/master/src/common/core.plugins.js
MIT
async deactivate(payload) { return undefined; }
Deactivate the plugin. @param {{ state: UserState, }} payload
deactivate
javascript
ineo6/git-master
src/common/core.plugins.js
https://github.com/ineo6/git-master/blob/master/src/common/core.plugins.js
MIT
async applyOptions(changes) { return false; }
Applies the option changes user has made. @param {!Object<!string, [(string|boolean), (string|boolean)]>} changes @return {!Promise<boolean>} iff the tree should be reloaded.
applyOptions
javascript
ineo6/git-master
src/common/core.plugins.js
https://github.com/ineo6/git-master/blob/master/src/common/core.plugins.js
MIT
async function treeTruncate() { $.jstree.defaults.truncate = $.noop; $.jstree.plugins.truncate = function(opts, parent) { this.redraw_node = function(obj, deep, callback, forceDraw) { obj = parent.redraw_node.call(this, obj, deep, callback, forceDraw); let anchor = null; if (obj) { anchor = $(obj).children('.jstree-anchor'); if (anchor.length) { // wrap content anchor .contents() .filter(function() { // Get text node which is path name return this.nodeType === 3; }) .wrap('<div style="overflow: hidden;text-overflow: ellipsis;"></div>') .end(); anchor.children().wrapAll('<div class="jstree-anchor-inner"></div>'); extStore.get(STORE.FILESIZE).then(showFileSize => { if (showFileSize) { let sizeInfo = ''; const anchorData = anchor.data(); if (anchorData.fileCount) { sizeInfo = `<span class="gm-tree-file-info">${anchorData.fileCount}</span>`; } else if (anchorData.fileSize) { sizeInfo = `<span class="gm-tree-file-info">${anchorData.fileSize}</span>`; } // append size anchor.addClass('gm-show-file-info'); anchor.append(sizeInfo); } }); } } return obj; }; }; }
Mimic logic from JSTree https://github.com/vakata/jstree/blob/master/src/misc.js#L148 Plugin truncate path name
treeTruncate
javascript
ineo6/git-master
src/common/util.plugins.js
https://github.com/ineo6/git-master/blob/master/src/common/util.plugins.js
MIT
loadElements() { this.elements = this.$view.find('[data-store]').toArray(); }
Load elements with [data-store] attributes & attach enforeShowInRule to the elements in the show in section. Invoke this if there are dynamically added elements, so that they can be loaded and saved.
loadElements
javascript
ineo6/git-master
src/common/view.options.js
https://github.com/ineo6/git-master/blob/master/src/common/view.options.js
MIT
handleTabClick(e) { const current = $(this); const index = current.index(); this.setTab(index); }
Toggles the visibility of this screen.
handleTabClick
javascript
ineo6/git-master
src/common/view.options.js
https://github.com/ineo6/git-master/blob/master/src/common/view.options.js
MIT
setTab(index) { const current = this.$view.find(`.master-tabs-tab:eq(${index})`); const width = current.outerWidth(true); current.removeClass('master-tabs-tab-disabled').addClass('master-tabs-tab-active'); const link = this.$view.find('.master-tabs-ink-bar'); const content = this.$view.find('.master-tabs-content'); // link.css({ // transform: `translate3d(${index * 51}px, 0px, 0px)`, // }); content.css({ 'margin-left': `-${index * 100}%`, }); }
Toggles the visibility of this screen.
setTab
javascript
ineo6/git-master
src/common/view.options.js
https://github.com/ineo6/git-master/blob/master/src/common/view.options.js
MIT
changeDarkModeWrapper(e) { this.changeDarkMode(false, e); }
Toggles the visibility of this screen.
changeDarkModeWrapper
javascript
ineo6/git-master
src/common/view.options.js
https://github.com/ineo6/git-master/blob/master/src/common/view.options.js
MIT
changeDarkMode(init, e) { parallel( [1], async (elm, cb) => { const mode = 'gm-default-theme-' + this.whoami; let value = await extStore.get(STORE.DARKMODE); if (!init) { value = !value; await extStore.set(STORE.DARKMODE, value); } if (value) { $('html').addClass([mode, shareClassName.sidebarDarkCls].join(' ')); } else { $('html').removeClass([mode, shareClassName.sidebarDarkCls].join(' ')); } report.send(report.event.DARK_MODE, { action: this.whoami, value: value ? 1 : 0, }); }, () => {} ); }
Toggles the visibility of this screen.
changeDarkMode
javascript
ineo6/git-master
src/common/view.options.js
https://github.com/ineo6/git-master/blob/master/src/common/view.options.js
MIT
async clearBuildInDarkMode() { const value = await extStore.get(STORE.DARKMODE); const mode = 'gm-default-theme-' + this.whoami; if (value) { // dark mode off $('html').removeClass([mode, shareClassName.sidebarDarkCls].join(' ')); await extStore.set(STORE.DARKMODE, !value); } // load other const githubIsDark = isGitHubInDark(); if (githubIsDark) { $('html').addClass(shareClassName.sidebarDarkCls); } report.send(report.event.DISABLE_BUILD_IN_DARK, { action: this.whoami, value: value ? 1 : 0, }); }
Toggles the visibility of this screen.
clearBuildInDarkMode
javascript
ineo6/git-master
src/common/view.options.js
https://github.com/ineo6/git-master/blob/master/src/common/view.options.js
MIT
changeDirectionWrapper(e) { this.changeDirection(false, e); }
Toggles the visibility of this screen.
changeDirectionWrapper
javascript
ineo6/git-master
src/common/view.options.js
https://github.com/ineo6/git-master/blob/master/src/common/view.options.js
MIT
_load() { this._eachOption( ($elm, key, value, cb) => { if ($elm.is(':checkbox')) { $elm.prop('checked', value); } else if ($elm.is(':radio')) { $elm.prop('checked', $elm.val() === value); } else { $elm.val(value); } cb(); }, () => { this.$toggler.addClass('selected'); $(this).trigger(EVENT.VIEW_READY); } ); }
Toggles the visibility of this screen.
_load
javascript
ineo6/git-master
src/common/view.options.js
https://github.com/ineo6/git-master/blob/master/src/common/view.options.js
MIT
_save() { const changes = {}; this._eachOption( async ($elm, key, value, cb) => { if ($elm.is(':radio') && !$elm.is(':checked')) { return cb(); } const newValue = $elm.is(':checkbox') ? $elm.is(':checked') : $elm.val(); if (value === newValue) return cb(); changes[key] = [value, newValue]; await extStore.set(key, newValue); cb(); }, () => { this.initDarkModeBtn(false); } ); }
Toggles the visibility of this screen.
_save
javascript
ineo6/git-master
src/common/view.options.js
https://github.com/ineo6/git-master/blob/master/src/common/view.options.js
MIT
_eachOption(processFn, completeFn) { parallel( this.elements, async (elm, cb) => { const $elm = $(elm); const key = STORE[$elm.data('store')]; const value = await extStore.get(key); processFn($elm, key, value, () => cb()); }, completeFn ); }
Toggles the visibility of this screen.
_eachOption
javascript
ineo6/git-master
src/common/view.options.js
https://github.com/ineo6/git-master/blob/master/src/common/view.options.js
MIT
async initDarkModeBtn(init = true) { // disable when build-in is false const isBuildInDark = await extStore.get(STORE.BUILD_IN_DARK); if ([DICT.GITHUB, DICT.GIST].includes(this.whoami) && isBuildInDark) { !init && unSubscribeDarkMode(); this.$darkMode.show(); } else { if (!isBuildInDark && !init) { subscribeDarkModeAndChange(); } this.$darkMode.hide(); !init && this.clearBuildInDarkMode(); } }
Toggles the visibility of this screen.
initDarkModeBtn
javascript
ineo6/git-master
src/common/view.options.js
https://github.com/ineo6/git-master/blob/master/src/common/view.options.js
MIT
onItemClick(event) { return false; }
Intercept the _onItemClick method return true to stop the current execution @param {Event} event
onItemClick
javascript
ineo6/git-master
src/common/view.tree.js
https://github.com/ineo6/git-master/blob/master/src/common/view.tree.js
MIT
_onItemClick(event) { let $target = $(event.target); let download = false; // Handle middle click if (event.which === 2) return; if (this.onItemClick(event)) return; if ($target.is('i.jstree-icon')) { $target = $target.parent(); download = true; } else if (!$target.is('a.jstree-anchor')) { $target = $target.closest('a.jstree-anchor'); } $target = $target.is('a.jstree-anchor') ? $target : $target.parent(); if ($target.is('.gitmaster-patch')) { $target = $target.parent(); } if (!$target.is('a.jstree-anchor')) return; // Refocus after complete so that keyboard navigation works, fix #158 const refocusAfterCompletion = () => { $(document).one('pjax:success page:load', () => { this.$jstree.get_container().focus(); }); }; const adapter = this.adapter; const newTab = event.shiftKey || event.ctrlKey || event.metaKey; const href = $target.attr('href'); // The 2nd path is for submodule child links const targetInner = $target.find('.jstree-anchor-inner'); const $icon = targetInner.children().length ? targetInner.children(':first') : targetInner.siblings(':first'); if ($icon.hasClass('commit')) { refocusAfterCompletion(); newTab ? adapter.openInNewTab(href) : adapter.selectSubmodule(href); } else if ($icon.hasClass('blob')) { if (download) { const downloadUrl = $target.attr('data-download-url'); const downloadFileName = $target.attr('data-download-filename'); adapter.downloadFile(downloadUrl, downloadFileName); } else { refocusAfterCompletion(); newTab ? adapter.openInNewTab(href) : adapter.selectFile(href); } } }
Intercept the _onItemClick method return true to stop the current execution @param {Event} event
_onItemClick
javascript
ineo6/git-master
src/common/view.tree.js
https://github.com/ineo6/git-master/blob/master/src/common/view.tree.js
MIT
refocusAfterCompletion = () => { $(document).one('pjax:success page:load', () => { this.$jstree.get_container().focus(); }); }
Intercept the _onItemClick method return true to stop the current execution @param {Event} event
refocusAfterCompletion
javascript
ineo6/git-master
src/common/view.tree.js
https://github.com/ineo6/git-master/blob/master/src/common/view.tree.js
MIT
refocusAfterCompletion = () => { $(document).one('pjax:success page:load', () => { this.$jstree.get_container().focus(); }); }
Intercept the _onItemClick method return true to stop the current execution @param {Event} event
refocusAfterCompletion
javascript
ineo6/git-master
src/common/view.tree.js
https://github.com/ineo6/git-master/blob/master/src/common/view.tree.js
MIT
breakPath(fullPath) { return fullPath.split('/').reduce((res, path, idx) => { res.push(idx === 0 ? path : `${res[idx - 1]}/${path}`); return res; }, []); }
Intercept the _onItemClick method return true to stop the current execution @param {Event} event
breakPath
javascript
ineo6/git-master
src/common/view.tree.js
https://github.com/ineo6/git-master/blob/master/src/common/view.tree.js
MIT
parserGitLabRepoPath(path) { const match = path.match(/(?:[^/]+\/)+blob\/(?:[^/]+\/)(.*)/); if (match && match.length === 2) { return match[1]; } return ''; }
Intercept the _onItemClick method return true to stop the current execution @param {Event} event
parserGitLabRepoPath
javascript
ineo6/git-master
src/common/view.tree.js
https://github.com/ineo6/git-master/blob/master/src/common/view.tree.js
MIT
parserGiteeRepoPath(path) { const match = path.match(/(?:[^/]+\/)+branch\/(?:[^/]+\/)(.*)/); if (match && match.length === 2) { return match[1]; } return ''; }
Intercept the _onItemClick method return true to stop the current execution @param {Event} event
parserGiteeRepoPath
javascript
ineo6/git-master
src/common/view.tree.js
https://github.com/ineo6/git-master/blob/master/src/common/view.tree.js
MIT
parserRepoPath(path) { const match = path.match(/(?:[^/]+\/){4}(.*)/); if (match && match.length === 2) { return match[1]; } return ''; }
Intercept the _onItemClick method return true to stop the current execution @param {Event} event
parserRepoPath
javascript
ineo6/git-master
src/common/view.tree.js
https://github.com/ineo6/git-master/blob/master/src/common/view.tree.js
MIT
getCurrentFilePath() { const path = decodeURIComponent(window.location.pathname); if (this.adapter.whoami() === DICT.GITLAB) { return this.parserGitLabRepoPath(path); } else if (this.adapter.whoami() === DICT.GITEA) { return this.parserGiteeRepoPath(path); } return this.parserRepoPath(path); }
Intercept the _onItemClick method return true to stop the current execution @param {Event} event
getCurrentFilePath
javascript
ineo6/git-master
src/common/view.tree.js
https://github.com/ineo6/git-master/blob/master/src/common/view.tree.js
MIT
async syncSelection(repo) { const $jstree = this.$jstree; if (!$jstree) return; const currentPath = this.getCurrentFilePath(); if (currentPath === '') { return; } const loadAll = await this.adapter.shouldLoadEntireTree(repo); this.selectPath(loadAll ? [currentPath] : this.breakPath(currentPath)); }
Intercept the _onItemClick method return true to stop the current execution @param {Event} event
syncSelection
javascript
ineo6/git-master
src/common/view.tree.js
https://github.com/ineo6/git-master/blob/master/src/common/view.tree.js
MIT
selectPath(paths, index = 0) { const nodeId = NODE_PREFIX + paths[index]; const $jstree = this.$jstree; if ($jstree.get_node(nodeId)) { $jstree.deselect_all(); $jstree.select_node(nodeId); $jstree.open_node(nodeId, () => { if (++index < paths.length) { this.selectPath(paths, index); } }); } }
Intercept the _onItemClick method return true to stop the current execution @param {Event} event
selectPath
javascript
ineo6/git-master
src/common/view.tree.js
https://github.com/ineo6/git-master/blob/master/src/common/view.tree.js
MIT
_loadCodeTreeInternal(opts, transform, cb) { const folders = { '': [] }; const { path, repo, node } = opts; opts.encodedBranch = opts.encodedBranch || encodeURIComponent(decodeURIComponent(repo.branch)); this._getTree(path, opts, (err, tree) => { if (err) return cb(err); const treeMap = this.collectTree(tree); this._getSubmodules(tree, opts, (err, submodules) => { if (err) return cb(err); // eslint-disable-next-line no-param-reassign submodules = submodules || {}; // eslint-disable-next-line complexity const nextChunk = async (iteration = 0) => { const CHUNK_SIZE = 300; for (let i = 0; i < CHUNK_SIZE; i++) { let item = tree[iteration * CHUNK_SIZE + i]; // We're done if (item === undefined) { let treeData = folders['']; treeData = this._sort(treeData); if (!opts.node) { treeData = this._collapse(treeData); } return cb(null, treeData); } // Runs transform requested by subclass if (transform) { item = transform(item); } // If lazy load and has parent, prefix with parent path // gitlab default is lazyload // so gitlab url should not append parent path if (node && node.path) { if (!item.path.startsWith(`${node.path}/`)) { item.path = node.path + '/' + item.path; } } const path = item.path || ''; const type = item.type; const index = path.lastIndexOf('/'); const name = deXss(path.substring(index + 1)); // Sanitizes, closes #9 const attr = {}; item.id = NODE_PREFIX + path; item.text = name; item.li_attr = { title: path, }; // Uses `type` as class name for tree node item.icon = type; // eslint-disable-next-line no-await-in-loop await gitMaster.setNodeIconAndText(this, item); if (item.patch) { item.text += `<span class="gitmaster-patch">${this.buildPatchHtml(item)}</span>`; } if (node) { folders[''].push(item); } else { folders[path.substring(0, index)].push(item); } if (type === 'tree' || type === 'blob') { if (type === 'tree') { if (node) { item.children = true; } else { // eslint-disable-next-line no-multi-assign folders[item.path] = item.children = []; } if (treeMap[path]) { attr['data-file-count'] = treeMap[path]; } } else if (type === 'blob' && item.size) { const parsedSize = convertSizeToHumanReadableFormat(item.size, 0); attr['data-file-size'] = parsedSize.size + parsedSize.measure; } // If item is part of a PR, jump to that file's diff if (item.patch && typeof item.patch.diffId === 'number') { const url = this._getPatchHref(repo, item.patch); attr.href = url; attr['data-download-url'] = item.url; attr['data-download-filename'] = name; } else { // Encodes but retains the slashes, see #274 const encodedPath = path .split('/') .map(encodeURIComponent) .join('/'); const url = this.getItemHref(repo, type, encodedPath, opts.encodedBranch); attr.href = url; attr['data-download-url'] = url; attr['data-download-filename'] = name; } } else if (type === 'commit') { let moduleUrl = submodules[item.path]; if (moduleUrl) { // Fixes #105 // Special handling for submodules hosted in GitHub // eslint-disable-next-line no-bitwise if (moduleUrl.indexOf('github.com') !== -1) { moduleUrl = moduleUrl .replace(/^git(:\/\/|@)/, window.location.protocol + '//') .replace('github.com:', 'github.com/') .replace(/.git$/, '') + '/tree/' + item.sha; item.text = `${name} @ ${item.sha.substr(0, 7)}`; } attr.href = moduleUrl; attr['data-skip-pjax'] = true; } } item.a_attr = attr; } setTimeout(() => nextChunk(iteration + 1)); }; nextChunk(); }); }); }
Loads the code tree of a repository. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null/false to load entire tree), token (optional): the personal access token } @param {Function} transform(item) @param {Function} cb(err: error, tree: Array[Array|item]) @api protected
_loadCodeTreeInternal
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
nextChunk = async (iteration = 0) => { const CHUNK_SIZE = 300; for (let i = 0; i < CHUNK_SIZE; i++) { let item = tree[iteration * CHUNK_SIZE + i]; // We're done if (item === undefined) { let treeData = folders['']; treeData = this._sort(treeData); if (!opts.node) { treeData = this._collapse(treeData); } return cb(null, treeData); } // Runs transform requested by subclass if (transform) { item = transform(item); } // If lazy load and has parent, prefix with parent path // gitlab default is lazyload // so gitlab url should not append parent path if (node && node.path) { if (!item.path.startsWith(`${node.path}/`)) { item.path = node.path + '/' + item.path; } } const path = item.path || ''; const type = item.type; const index = path.lastIndexOf('/'); const name = deXss(path.substring(index + 1)); // Sanitizes, closes #9 const attr = {}; item.id = NODE_PREFIX + path; item.text = name; item.li_attr = { title: path, }; // Uses `type` as class name for tree node item.icon = type; // eslint-disable-next-line no-await-in-loop await gitMaster.setNodeIconAndText(this, item); if (item.patch) { item.text += `<span class="gitmaster-patch">${this.buildPatchHtml(item)}</span>`; } if (node) { folders[''].push(item); } else { folders[path.substring(0, index)].push(item); } if (type === 'tree' || type === 'blob') { if (type === 'tree') { if (node) { item.children = true; } else { // eslint-disable-next-line no-multi-assign folders[item.path] = item.children = []; } if (treeMap[path]) { attr['data-file-count'] = treeMap[path]; } } else if (type === 'blob' && item.size) { const parsedSize = convertSizeToHumanReadableFormat(item.size, 0); attr['data-file-size'] = parsedSize.size + parsedSize.measure; } // If item is part of a PR, jump to that file's diff if (item.patch && typeof item.patch.diffId === 'number') { const url = this._getPatchHref(repo, item.patch); attr.href = url; attr['data-download-url'] = item.url; attr['data-download-filename'] = name; } else { // Encodes but retains the slashes, see #274 const encodedPath = path .split('/') .map(encodeURIComponent) .join('/'); const url = this.getItemHref(repo, type, encodedPath, opts.encodedBranch); attr.href = url; attr['data-download-url'] = url; attr['data-download-filename'] = name; } } else if (type === 'commit') { let moduleUrl = submodules[item.path]; if (moduleUrl) { // Fixes #105 // Special handling for submodules hosted in GitHub // eslint-disable-next-line no-bitwise if (moduleUrl.indexOf('github.com') !== -1) { moduleUrl = moduleUrl .replace(/^git(:\/\/|@)/, window.location.protocol + '//') .replace('github.com:', 'github.com/') .replace(/.git$/, '') + '/tree/' + item.sha; item.text = `${name} @ ${item.sha.substr(0, 7)}`; } attr.href = moduleUrl; attr['data-skip-pjax'] = true; } } item.a_attr = attr; } setTimeout(() => nextChunk(iteration + 1)); }
Loads the code tree of a repository. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null/false to load entire tree), token (optional): the personal access token } @param {Function} transform(item) @param {Function} cb(err: error, tree: Array[Array|item]) @api protected
nextChunk
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
nextChunk = async (iteration = 0) => { const CHUNK_SIZE = 300; for (let i = 0; i < CHUNK_SIZE; i++) { let item = tree[iteration * CHUNK_SIZE + i]; // We're done if (item === undefined) { let treeData = folders['']; treeData = this._sort(treeData); if (!opts.node) { treeData = this._collapse(treeData); } return cb(null, treeData); } // Runs transform requested by subclass if (transform) { item = transform(item); } // If lazy load and has parent, prefix with parent path // gitlab default is lazyload // so gitlab url should not append parent path if (node && node.path) { if (!item.path.startsWith(`${node.path}/`)) { item.path = node.path + '/' + item.path; } } const path = item.path || ''; const type = item.type; const index = path.lastIndexOf('/'); const name = deXss(path.substring(index + 1)); // Sanitizes, closes #9 const attr = {}; item.id = NODE_PREFIX + path; item.text = name; item.li_attr = { title: path, }; // Uses `type` as class name for tree node item.icon = type; // eslint-disable-next-line no-await-in-loop await gitMaster.setNodeIconAndText(this, item); if (item.patch) { item.text += `<span class="gitmaster-patch">${this.buildPatchHtml(item)}</span>`; } if (node) { folders[''].push(item); } else { folders[path.substring(0, index)].push(item); } if (type === 'tree' || type === 'blob') { if (type === 'tree') { if (node) { item.children = true; } else { // eslint-disable-next-line no-multi-assign folders[item.path] = item.children = []; } if (treeMap[path]) { attr['data-file-count'] = treeMap[path]; } } else if (type === 'blob' && item.size) { const parsedSize = convertSizeToHumanReadableFormat(item.size, 0); attr['data-file-size'] = parsedSize.size + parsedSize.measure; } // If item is part of a PR, jump to that file's diff if (item.patch && typeof item.patch.diffId === 'number') { const url = this._getPatchHref(repo, item.patch); attr.href = url; attr['data-download-url'] = item.url; attr['data-download-filename'] = name; } else { // Encodes but retains the slashes, see #274 const encodedPath = path .split('/') .map(encodeURIComponent) .join('/'); const url = this.getItemHref(repo, type, encodedPath, opts.encodedBranch); attr.href = url; attr['data-download-url'] = url; attr['data-download-filename'] = name; } } else if (type === 'commit') { let moduleUrl = submodules[item.path]; if (moduleUrl) { // Fixes #105 // Special handling for submodules hosted in GitHub // eslint-disable-next-line no-bitwise if (moduleUrl.indexOf('github.com') !== -1) { moduleUrl = moduleUrl .replace(/^git(:\/\/|@)/, window.location.protocol + '//') .replace('github.com:', 'github.com/') .replace(/.git$/, '') + '/tree/' + item.sha; item.text = `${name} @ ${item.sha.substr(0, 7)}`; } attr.href = moduleUrl; attr['data-skip-pjax'] = true; } } item.a_attr = attr; } setTimeout(() => nextChunk(iteration + 1)); }
Loads the code tree of a repository. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null/false to load entire tree), token (optional): the personal access token } @param {Function} transform(item) @param {Function} cb(err: error, tree: Array[Array|item]) @api protected
nextChunk
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
getCssClass() { throw new Error('Not implemented'); }
Returns the CSS class to be added to sidebar. @api public
getCssClass
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
getMinWidth() { return 220; }
Returns the minimum width acceptable for the sidebar. @api protected
getMinWidth
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
init($sidebar) { $sidebar.resizable({ handles: 'e,w', minWidth: this.getMinWidth(), }); }
Inits behaviors after the sidebar is added to the DOM. @api public
init
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
async shouldLoadEntireTree(opts) { return false; }
Returns whether we should load the entire tree in a single request. @api public
shouldLoadEntireTree
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
loadCodeTree(opts, cb) { throw new Error('Not implemented'); }
Loads the code tree. @api public
loadCodeTree
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
getCreateTokenUrl() { throw new Error('Not implemented'); }
Returns the URL to create a personal access token. @api public
getCreateTokenUrl
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
updateLayout(sidebarPinned, sidebarVisible, sidebarWidth, isSidebarLeft) { throw new Error('Not implemented'); }
Updates the layout based on sidebar visibility and width. @api public
updateLayout
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
getRepoFromPath(token, cb) { throw new Error('Not implemented'); }
Returns repo info at the current path. @api public
getRepoFromPath
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
selectFile(path) { if (!isSafari()) { // Smooth scroll to diff file on PR page if (path.match(/#diff-\d+$/)) { const index = Number(path.split('-').slice(-1)[0]); const matchDom = $('#files .file').eq(index); if (matchDom.length) { $('html, body').animate({ scrollTop: matchDom.offset().top - 68 }, 400); return; } } } window.location.href = path; }
Selects the file at a specific path. @api public
selectFile
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
openInNewTab(path) { window.open(path, '_blank').focus(); }
Opens file or submodule in a new tab. @api public
openInNewTab
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
buildPatchHtml(treeItem = {}) { const { action, previous, filesChanged: files, additions, deletions } = treeItem.patch; let patch = ''; patch += action === 'added' ? '<span class="text-green">added</span>' : ''; patch += action === 'renamed' ? `<span class="text-green" title="${previous}">renamed</span>` : ''; patch += action === 'removed' ? `<span class="text-red" title="${previous}">removed</span>` : ''; patch += files ? `<span class='gitmaster-patch-files'>${files} ${files === 1 ? 'file' : 'files'}</span>` : ''; patch += additions !== 0 ? `<span class="text-green">+${additions}</span>` : ''; patch += deletions !== 0 ? `<span class="text-red">-${deletions}</span>` : ''; return patch; }
@param {HTML Text} patch @param {Object} treeItem Return the patch Html for tree item
buildPatchHtml
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
_getTree(path, opts, cb) { throw new Error('Not implemented'); }
Gets tree at path. @param {Object} opts - {token, repo} @api protected
_getTree
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
_getSubmodules(tree, opts, cb) { throw new Error('Not implemented'); }
Gets submodules in the tree. @param {Object} opts - {token, repo, encodedBranch} @api protected
_getSubmodules
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
getAccessToken() { throw new Error('Not implemented'); }
Gets submodules in the tree. @param {Object} opts - {token, repo, encodedBranch} @api protected
getAccessToken
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
getItemHref(repo, type, encodedPath, encodedBranch) { return `/${repo.username}/${repo.reponame}/${type}/${encodedBranch}/${encodedPath}`; }
Returns item's href value. @api public
getItemHref
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
_getPatchHref(repo, patch) { return `/${repo.username}/${repo.reponame}/pull/${repo.pullNumber}/files#diff-${patch.diffId}`; }
Returns patch's href value. @api protected
_getPatchHref
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
_sort(folder) { folder.sort((a, b) => { // eslint-disable-next-line no-nested-ternary if (a.type === b.type) return a.text === b.text ? 0 : a.text < b.text ? -1 : 1; return a.type === 'blob' ? 1 : -1; }); folder.forEach(item => { if (item.type === 'tree' && item.children !== true && item.children.length > 0) { this._sort(item.children); } }); return folder; }
Returns patch's href value. @api protected
_sort
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
_collapse(folder) { return folder.map(item => { if (item.type === 'tree') { item.children = this._collapse(item.children); if (item.children.length === 1 && item.children[0].type === 'tree' && item.a_attr) { const onlyChild = item.children[0]; const path = item.a_attr['data-download-filename']; onlyChild.text = path + '/' + onlyChild.text; return onlyChild; } } return item; }); }
Returns patch's href value. @api protected
_collapse
javascript
ineo6/git-master
src/common/adapters/adapter.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/adapter.js
MIT
_getPatch(opts, cb) { const { pullNumber } = opts.repo; this._get(`/pulls/${pullNumber}/files?per_page=300`, opts, (err, res) => { if (err) { cb(err); } else { const diffMap = {}; res.forEach((file, index) => { // Record file patch info diffMap[file.filename] = { type: 'blob', diffId: index, action: file.status, additions: file.additions, blob_url: file.blob_url, deletions: file.deletions, filename: file.filename, path: file.path, sha: file.sha, }; // Record ancestor folders const folderPath = file.filename .split('/') .slice(0, -1) .join('/'); const split = folderPath.split('/'); // Aggregate metadata for ancestor folders split.reduce((path, curr) => { if (path.length) { path = `${path}/${curr}`; } else { path = `${curr}`; } if (diffMap[path] == null) { diffMap[path] = { type: 'tree', filename: path, filesChanged: 1, additions: file.additions, deletions: file.deletions, }; } else { diffMap[path].additions += file.additions; diffMap[path].deletions += file.deletions; diffMap[path].filesChanged++; } return path; }, ''); }); // Transform to emulate response from get `tree` const tree = Object.keys(diffMap).map(fileName => { const patch = diffMap[fileName]; return { patch, path: fileName, sha: patch.sha, type: patch.type, url: patch.blob_url, }; }); // Sort by path, needs to be alphabetical order (so parent folders come before children) // Note: this is still part of the above transform to mimic the behavior of get tree tree.sort((a, b) => a.path.localeCompare(b.path)); cb(null, tree); } }); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
_getPatch
javascript
ineo6/git-master
src/common/adapters/gist.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gist.js
MIT
async loadRepoData(path, isRepoMetaData = false) { const token = await this.getAccessToken(); try { const repo = await this.getRepoDataWrap(false, token); if (repo) { const data = await this.getContent(path, { repo, isRepoMetaData, }); return { repo, contentData: data, }; } } catch (e) { return false; } }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
loadRepoData
javascript
ineo6/git-master
src/common/adapters/gist.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gist.js
MIT
async getGists(path, opts) { opts.token = await this.getAccessToken(); return new Promise(resolve => { this._getTree(path, opts, (err, tree) => { resolve(tree); }); }); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
getGists
javascript
ineo6/git-master
src/common/adapters/gist.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gist.js
MIT
_get(path, opts, cb) { const host = window.location.protocol + '//' + (window.location.host === 'gist.github.com' ? 'api.github.com' : window.location.host + '/api/v3'); let url = `${host}/gists/${opts.repo.gistId}${path ? '/' + path : ''}`; const cfg = { url, method: 'GET', cache: true, }; if (opts.token) { cfg.headers = { Authorization: 'token ' + opts.token }; } $.ajax(cfg) .done((data, textStatus, jqXHR) => { (async () => { cb(null, data, jqXHR); })(); }) .fail(jqXHR => this._handleError(cfg, jqXHR, cb)); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
_get
javascript
ineo6/git-master
src/common/adapters/gist.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gist.js
MIT
_getPatch(opts, cb) { const { pullNumber } = opts.repo; this._get(`/pulls/${pullNumber}/files?per_page=300`, opts, (err, res) => { if (err) { cb(err); } else { const diffMap = {}; res.forEach((file, index) => { // Record file patch info diffMap[file.filename] = { type: 'blob', diffId: index, action: file.status, additions: file.additions, blob_url: file.blob_url, deletions: file.deletions, filename: file.filename, path: file.path, sha: file.sha, }; // Record ancestor folders const folderPath = file.filename .split('/') .slice(0, -1) .join('/'); const split = folderPath.split('/'); // Aggregate metadata for ancestor folders split.reduce((path, curr) => { if (path.length) { path = `${path}/${curr}`; } else { path = `${curr}`; } if (diffMap[path] == null) { diffMap[path] = { type: 'tree', filename: path, filesChanged: 1, additions: file.additions, deletions: file.deletions, }; } else { diffMap[path].additions += file.additions; diffMap[path].deletions += file.deletions; diffMap[path].filesChanged++; } return path; }, ''); }); // Transform to emulate response from get `tree` const tree = Object.keys(diffMap).map(fileName => { const patch = diffMap[fileName]; return { patch, path: fileName, sha: patch.sha, type: patch.type, url: patch.blob_url, }; }); // Sort by path, needs to be alphabetical order (so parent folders come before children) // Note: this is still part of the above transform to mimic the behavior of get tree tree.sort((a, b) => a.path.localeCompare(b.path)); cb(null, tree); } }); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
_getPatch
javascript
ineo6/git-master
src/common/adapters/gitea.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gitea.js
MIT
_getSubmodules(tree, opts, cb) { const item = tree.filter(item => /^\.gitmodules$/i.test(item.path))[0]; if (!item) return cb(); this._get(`/git/blobs/${item.sha}`, opts, (err, res) => { if (err) return cb(err); const data = atob(res.content.replace(/\n/g, '')); cb(null, parseGitmodules(data)); }); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
_getSubmodules
javascript
ineo6/git-master
src/common/adapters/gitea.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gitea.js
MIT
async loadRepoData(path, isRepoMetaData = false) { const token = await this.getAccessToken(); try { const repo = await this.getRepoDataWrap(false, token); if (repo) { const data = await this.getContent(path, { repo, isRepoMetaData, }); return { repo, contentData: data, }; } } catch (e) { return false; } }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
loadRepoData
javascript
ineo6/git-master
src/common/adapters/gitea.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gitea.js
MIT
getContentPath() { let str = window.location.href; let result = str.match(/.*[bt][lr][oe][be]\/[^//]+\/(.*)/); // blob/tree :D return result && result.length && result[1]; }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
getContentPath
javascript
ineo6/git-master
src/common/adapters/gitea.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gitea.js
MIT
async getContent(path, opts) { const host = window.location.protocol + '//' + (window.location.host === 'github.com' ? 'api.github.com' : window.location.host + '/api/v1'); const url = `${host}/repos/${opts.repo.username}/${opts.repo.reponame}`; const contentPath = path || this.getContentPath() || ''; let contentParams = ''; const branch = encodeURIComponent(decodeURIComponent(opts.repo.branch)); if (!opts.isRepoMetaData) { contentParams = '/contents/' + contentPath + '?ref=' + branch; } const cfg = { url: `${url}${contentParams}`, method: 'GET', cache: false, }; const token = await this.getAccessToken(); if (token) { cfg.headers = { Authorization: 'token ' + token }; } return new Promise((resolve, reject) => { $.ajax(cfg) .done((data, textStatus, jqXHR) => { resolve(data, jqXHR); }) .fail(jqXHR => this._handleError(cfg, jqXHR, resolve)); }); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
getContent
javascript
ineo6/git-master
src/common/adapters/gitea.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gitea.js
MIT
_get(path, opts, cb) { let url; if (path && path.startsWith('http')) { url = path; } else { const host = window.location.protocol + '//' + window.location.host + '/api/v1'; url = `${host}/repos/${opts.repo.username}/${opts.repo.reponame}${path || ''}`; } const cfg = { url, method: 'GET', cache: false, }; if (opts.token) { cfg.headers = { Authorization: 'token ' + opts.token }; } $.ajax(cfg) .done((data, textStatus, jqXHR) => { (async () => { if (path && path.indexOf('/git/trees') === 0 && data.truncated) { try { const hugeRepos = await extStore.get(STORE.HUGE_REPOS); const repo = `${opts.repo.username}/${opts.repo.reponame}`; const repos = Object.keys(hugeRepos).filter(hugeRepoKey => isValidTimeStamp(hugeRepos[hugeRepoKey])); if (!hugeRepos[repo]) { // If there are too many repos memoized, delete the oldest one if (repos.length >= GH_MAX_HUGE_REPOS_SIZE) { const oldestRepo = repos.reduce((min, p) => (hugeRepos[p] < hugeRepos[min] ? p : min)); delete hugeRepos[oldestRepo]; } hugeRepos[repo] = new Date().getTime(); await extStore.set(STORE.HUGE_REPOS, hugeRepos); } // eslint-disable-next-line no-empty } catch (ignored) { } finally { await this._handleError(cfg, { status: 206 }, cb); } } else { cb(null, data, jqXHR); } })(); }) .fail(jqXHR => this._handleError(cfg, jqXHR, cb)); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
_get
javascript
ineo6/git-master
src/common/adapters/gitea.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gitea.js
MIT
async getRepoDataWrap(currentRepo, token) { if (!githubDetect.shouldEnable()) { return; } return new Promise((resolve, reject) => { this.getRepoData(currentRepo, token, (error, result) => { if (!error) { resolve(result); } if (typeof error === 'string') { resolve(''); } resolve(''); }); }); }
Github renders the branch name in one of below structure depending on the length of branch name. We're using this for default code page or tree/blob. Option 1: when the length is short enough <summary title="Switch branches or tags"> <span class="css-truncate-target">feature/1/2/3</span> </summary> Option 2: when the length is too long <summary title="feature/1/2/3/4/5/6/7/8"> <span class="css-truncate-target">feature/1/2/3...</span> </summary>
getRepoDataWrap
javascript
ineo6/git-master
src/common/adapters/github.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/github.js
MIT
async getRepoFromPath(currentRepo, token, cb) { if (!githubDetect.shouldEnable()) { return cb(); } await this.getRepoData(currentRepo, token, cb); }
Github renders the branch name in one of below structure depending on the length of branch name. We're using this for default code page or tree/blob. Option 1: when the length is short enough <summary title="Switch branches or tags"> <span class="css-truncate-target">feature/1/2/3</span> </summary> Option 2: when the length is too long <summary title="feature/1/2/3/4/5/6/7/8"> <span class="css-truncate-target">feature/1/2/3...</span> </summary>
getRepoFromPath
javascript
ineo6/git-master
src/common/adapters/github.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/github.js
MIT
loadCodeTree(opts, cb) { opts.encodedBranch = encodeURIComponent(decodeURIComponent(opts.repo.branch)); opts.path = (opts.node && (opts.node.sha || opts.encodedBranch)) || opts.encodedBranch + '?recursive=1'; this._loadCodeTreeInternal(opts, null, cb); }
Github renders the branch name in one of below structure depending on the length of branch name. We're using this for default code page or tree/blob. Option 1: when the length is short enough <summary title="Switch branches or tags"> <span class="css-truncate-target">feature/1/2/3</span> </summary> Option 2: when the length is too long <summary title="feature/1/2/3/4/5/6/7/8"> <span class="css-truncate-target">feature/1/2/3...</span> </summary>
loadCodeTree
javascript
ineo6/git-master
src/common/adapters/github.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/github.js
MIT
getAccessToken() { return window.extStore.get(window.STORE.GITHUB_TOKEN); }
Github renders the branch name in one of below structure depending on the length of branch name. We're using this for default code page or tree/blob. Option 1: when the length is short enough <summary title="Switch branches or tags"> <span class="css-truncate-target">feature/1/2/3</span> </summary> Option 2: when the length is too long <summary title="feature/1/2/3/4/5/6/7/8"> <span class="css-truncate-target">feature/1/2/3...</span> </summary>
getAccessToken
javascript
ineo6/git-master
src/common/adapters/github.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/github.js
MIT
get isOnPRPage() { // eslint-disable-next-line no-useless-escape const match = window.location.pathname.match(/([^\/]+)\/([^\/]+)(?:\/([^\/]+))?(?:\/([^\/]+))?/); if (!match) return false; const type = match[3]; return type === 'pull'; }
Github renders the branch name in one of below structure depending on the length of branch name. We're using this for default code page or tree/blob. Option 1: when the length is short enough <summary title="Switch branches or tags"> <span class="css-truncate-target">feature/1/2/3</span> </summary> Option 2: when the length is too long <summary title="feature/1/2/3/4/5/6/7/8"> <span class="css-truncate-target">feature/1/2/3...</span> </summary>
isOnPRPage
javascript
ineo6/git-master
src/common/adapters/github.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/github.js
MIT
_getTree(path, opts, cb) { if (opts.repo.pullNumber) { this._getPatch(opts, cb); } else { this._get(`/git/trees/${path}`, opts, (err, res) => { if (err) { cb(err); } else { cb(null, res.tree); } }); } }
Github renders the branch name in one of below structure depending on the length of branch name. We're using this for default code page or tree/blob. Option 1: when the length is short enough <summary title="Switch branches or tags"> <span class="css-truncate-target">feature/1/2/3</span> </summary> Option 2: when the length is too long <summary title="feature/1/2/3/4/5/6/7/8"> <span class="css-truncate-target">feature/1/2/3...</span> </summary>
_getTree
javascript
ineo6/git-master
src/common/adapters/github.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/github.js
MIT
_getPatch(opts, cb) { const { pullNumber } = opts.repo; this._get(`/pulls/${pullNumber}/files?per_page=300`, opts, (err, res) => { if (err) { cb(err); } else { const diffMap = {}; res.forEach((file, index) => { // Record file patch info diffMap[file.filename] = { type: 'blob', diffId: index, action: file.status, additions: file.additions, blob_url: file.blob_url, deletions: file.deletions, filename: file.filename, path: file.path, sha: file.sha, }; // Record ancestor folders const folderPath = file.filename .split('/') .slice(0, -1) .join('/'); const split = folderPath.split('/'); // Aggregate metadata for ancestor folders split.reduce((path, curr) => { if (path.length) { path = `${path}/${curr}`; } else { path = `${curr}`; } if (diffMap[path] == null) { diffMap[path] = { type: 'tree', filename: path, filesChanged: 1, additions: file.additions, deletions: file.deletions, }; } else { diffMap[path].additions += file.additions; diffMap[path].deletions += file.deletions; diffMap[path].filesChanged++; } return path; }, ''); }); // Transform to emulate response from get `tree` const tree = Object.keys(diffMap).map(fileName => { const patch = diffMap[fileName]; return { patch, path: fileName, sha: patch.sha, type: patch.type, url: patch.blob_url, }; }); // Sort by path, needs to be alphabetical order (so parent folders come before children) // Note: this is still part of the above transform to mimic the behavior of get tree tree.sort((a, b) => a.path.localeCompare(b.path)); cb(null, tree); } }); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
_getPatch
javascript
ineo6/git-master
src/common/adapters/github.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/github.js
MIT
_getSubmodules(tree, opts, cb) { const item = tree.filter(item => /^\.gitmodules$/i.test(item.path))[0]; if (!item) return cb(); this._get(`/git/blobs/${item.sha}`, opts, (err, res) => { if (err) return cb(err); const data = atob(res.content.replace(/\n/g, '')); cb(null, parseGitmodules(data)); }); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
_getSubmodules
javascript
ineo6/git-master
src/common/adapters/github.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/github.js
MIT
async loadRepoData(path, isRepoMetaData = false) { const token = await this.getAccessToken(); try { const repo = await this.getRepoDataWrap(false, token); if (repo) { const data = await this.getContent(path, { repo, isRepoMetaData, }); return { repo, contentData: data, }; } } catch (e) { return false; } }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
loadRepoData
javascript
ineo6/git-master
src/common/adapters/github.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/github.js
MIT
getContentPath() { let str = window.location.href; let result = str.match(/.*[bt][lr][oe][be]\/[^//]+\/(.*)/); // blob/tree :D return result && result.length && result[1]; }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
getContentPath
javascript
ineo6/git-master
src/common/adapters/github.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/github.js
MIT
async getContent(path, opts) { const host = window.location.protocol + '//' + (window.location.host === 'github.com' ? 'api.github.com' : window.location.host + '/api/v3'); const url = `${host}/repos/${opts.repo.username}/${opts.repo.reponame}`; const contentPath = path || this.getContentPath() || ''; let contentParams = ''; const branch = encodeURIComponent(decodeURIComponent(opts.repo.branch)); if (!opts.isRepoMetaData) { contentParams = '/contents/' + contentPath + '?ref=' + branch; } const cfg = { url: `${url}${contentParams}`, method: 'GET', cache: false, }; const token = await this.getAccessToken(); if (token) { cfg.headers = { Authorization: 'token ' + token }; } return new Promise((resolve, reject) => { $.ajax(cfg) .done((data, textStatus, jqXHR) => { resolve(data, jqXHR); }) .fail(jqXHR => this._handleError(cfg, jqXHR, resolve)); }); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
getContent
javascript
ineo6/git-master
src/common/adapters/github.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/github.js
MIT
_get(path, opts, cb) { let url; if (path && path.startsWith('http')) { url = path; } else { const host = window.location.protocol + '//' + (window.location.host === 'github.com' ? 'api.github.com' : window.location.host + '/api/v3'); url = `${host}/repos/${opts.repo.username}/${opts.repo.reponame}${path || ''}`; } const cfg = { url, method: 'GET', cache: false, }; if (opts.token) { cfg.headers = { Authorization: 'token ' + opts.token }; } $.ajax(cfg) .done((data, textStatus, jqXHR) => { (async () => { if (path && path.indexOf('/git/trees') === 0 && data.truncated) { try { const hugeRepos = await extStore.get(STORE.HUGE_REPOS); const repo = `${opts.repo.username}/${opts.repo.reponame}`; const repos = Object.keys(hugeRepos).filter(hugeRepoKey => isValidTimeStamp(hugeRepos[hugeRepoKey])); if (!hugeRepos[repo]) { // If there are too many repos memoized, delete the oldest one if (repos.length >= GH_MAX_HUGE_REPOS_SIZE) { const oldestRepo = repos.reduce((min, p) => (hugeRepos[p] < hugeRepos[min] ? p : min)); delete hugeRepos[oldestRepo]; } hugeRepos[repo] = new Date().getTime(); await extStore.set(STORE.HUGE_REPOS, hugeRepos); } // eslint-disable-next-line no-empty } catch (ignored) { } finally { await this._handleError(cfg, { status: 206 }, cb); } } else { cb(null, data, jqXHR); } })(); }) .fail(jqXHR => this._handleError(cfg, jqXHR, cb)); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
_get
javascript
ineo6/git-master
src/common/adapters/github.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/github.js
MIT
_getPatch(opts, cb) { const { pullNumber } = opts.repo; this._get(`/pulls/${pullNumber}/files?per_page=300`, opts, (err, res) => { if (err) { cb(err); } else { const diffMap = {}; res.forEach((file, index) => { // Record file patch info diffMap[file.filename] = { type: 'blob', diffId: index, action: file.status, additions: file.additions, blob_url: file.blob_url, deletions: file.deletions, filename: file.filename, path: file.path, sha: file.sha, }; // Record ancestor folders const folderPath = file.filename .split('/') .slice(0, -1) .join('/'); const split = folderPath.split('/'); // Aggregate metadata for ancestor folders split.reduce((path, curr) => { if (path.length) { path = `${path}/${curr}`; } else { path = `${curr}`; } if (diffMap[path] == null) { diffMap[path] = { type: 'tree', filename: path, filesChanged: 1, additions: file.additions, deletions: file.deletions, }; } else { diffMap[path].additions += file.additions; diffMap[path].deletions += file.deletions; diffMap[path].filesChanged++; } return path; }, ''); }); // Transform to emulate response from get `tree` const tree = Object.keys(diffMap).map(fileName => { const patch = diffMap[fileName]; return { patch, path: fileName, sha: patch.sha, type: patch.type, url: patch.blob_url, }; }); // Sort by path, needs to be alphabetical order (so parent folders come before children) // Note: this is still part of the above transform to mimic the behavior of get tree tree.sort((a, b) => a.path.localeCompare(b.path)); cb(null, tree); } }); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
_getPatch
javascript
ineo6/git-master
src/common/adapters/gitlab.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gitlab.js
MIT
_getSubmodules(tree, opts, cb) { // todo gitlab api not support fetch submodule return cb(); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
_getSubmodules
javascript
ineo6/git-master
src/common/adapters/gitlab.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gitlab.js
MIT
_get(path, opts, cb) { const repo = opts.repo; const version = this.isV3Gitlab() ? 'v3' : 'v4'; const host = `${window.location.protocol}//${window.location.host}/api/${version}`; const project = $('#search_project_id').val() || $('#project_id').val() || `${repo.username}%2f${repo.reponame}`; const url = `${host}/projects/${project}/repository${path || '/tree?'}&per_page=999&private_token=${opts.token}`; const cfg = { url, method: 'GET', cache: false, }; $.ajax(cfg) .done(data => cb(null, data)) .fail(jqXHR => this._handleError(cfg, jqXHR, cb)); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
_get
javascript
ineo6/git-master
src/common/adapters/gitlab.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gitlab.js
MIT
async _handleError(settings, jqXHR, cb) { let error; let message; switch (jqXHR.status) { case 0: error = 'Connection error'; message = `Cannot connect to website. If your network connection to this website is fine, maybe there is an outage of the API. Please try again later.`; break; case 401: error = 'Invalid token'; message = await gitMaster.getInvalidTokenMessage({ responseStatus: jqXHR.status, requestHeaders: settings.headers, }); break; case 404: if (jqXHR.responseJSON.message === '404 Tree Not Found') { error = 'Empty repository'; message = 'This repository is empty.'; } else { error = 'Private repository'; message = 'Accessing private repositories requires access token. ' + 'Please go to <a class="settings-btn">Settings</a> and enter a token.'; } break; case 403: if (jqXHR.getResponseHeader('RateLimit-Remaining') === '0') { // It's kinda specific for GitHub error = 'API limit exceeded'; message = 'You have exceeded the <a href="https://developer.github.com/v3/#rate-limiting">GitHub API rate limit</a>. ' + 'To continue using GitMaster, you need to provide a GitHub access token. ' + 'Please go to <a class="settings-btn">Settings</a> and enter a token.'; } else { error = 'Forbidden'; message = 'Accessing private repositories requires access token. ' + 'Please go to <a class="settings-btn">Settings</a> and enter a token.'; } break; // Fallback message default: // eslint-disable-next-line no-multi-assign error = message = jqXHR.statusText; break; } cb({ error: `Error: ${error}`, message: message, status: jqXHR.status, }); }
Get files that were patched in Pull Request. The diff map that is returned contains changed files, as well as the parents of the changed files. This allows the tree to be filtered for only folders that contain files with diffs. @param {Object} opts: { path: the starting path to load the tree, repo: the current repository, node (optional): the selected node (null to load entire tree), token (optional): the personal access token } @param {Function} cb(err: error, diffMap: Object)
_handleError
javascript
ineo6/git-master
src/common/adapters/gitlab.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gitlab.js
MIT
async getRepoDataWrap(currentRepo, token) { if (!detect.shouldEnable()) { return; } return new Promise((resolve, reject) => { this.getRepoData(currentRepo, token, (error, result) => { if (!error) { resolve(result); } if (typeof error === 'string') { resolve(''); } resolve(''); }); }); }
Github renders the branch name in one of below structure depending on the length of branch name. We're using this for default code page or tree/blob. Option 1: when the length is short enough <summary title="Switch branches or tags"> <span class="css-truncate-target">feature/1/2/3</span> </summary> Option 2: when the length is too long <summary title="feature/1/2/3/4/5/6/7/8"> <span class="css-truncate-target">feature/1/2/3...</span> </summary>
getRepoDataWrap
javascript
ineo6/git-master
src/common/adapters/gogs.js
https://github.com/ineo6/git-master/blob/master/src/common/adapters/gogs.js
MIT