Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
from visidata import Sheet, ColumnItem, asyncthread, globalCommand, ENTER
import vgit
class GitGrep(vgit.GitSheet):
rowtype = 'results' # rowdef: list(file, line, line_contents)
columns = [
ColumnItem('filename', 0),
ColumnItem('linenum', 1),
ColumnItem('line', 2),
]
@asyncthread
def reload(self):
tmp = (self.topRowIndex, self.cursorRowIndex)
self.rows = []
for line in self.git_lines('grep', '--no-color', '-z', '--line-number', '--ignore-case', self.regex):
self.addRow(line.split('\0'))
self.topRowIndex, self.cursorRowIndex = tmp
Sheet.unbindkey('g/')
globalCommand('g/', 'git-grep', 'rex=input("git grep: "); vd.push(GitGrep(rex, regex=rex, source=sheet))', 'find in all files in this repo'),
GitGrep.addCommand(ENTER, 'dive-row', 'vs=GitFileSheet(cursorRow[0]); vs.cursorRowIndex=int(cursorRow[1])-1; vs.reload(); vd.push(vs)', 'go to this match')
GitGrep.addCommand('^O', 'sysopen-row', 'launchExternalEditorPath(Path(cursorRow[0]), linenum=cursorRow[1]); reload()', 'open this file in $EDITOR')
def reload_sync(self):
'Perform synchronous loading of TSV file, discarding header lines.'
header_lines = options.get('header', self)
delim = options.get('delimiter', self)
with self.source.open_text() as fp:
# get one line anyway to determine number of columns
lines = list(getlines(fp, int(header_lines) or 1))
headers = [L.split(delim) for L in lines]
if header_lines <= 0:
self.columns = [ColumnItem('', i) for i in range(len(headers[0]))]
else:
self.columns = [
ColumnItem('\\n'.join(x), i)
for i, x in enumerate(zip(*headers[:header_lines]))
]
lines = lines[header_lines:] # in case of header_lines == 0
self._rowtype = namedlist('tsvobj', [c.name for c in self.columns])
self.recalc()
self.rows = []
with Progress(total=self.source.filesize) as prog:
for L in itertools.chain(lines, getlines(fp)):
row = L.split(delim)
ncols = self._rowtype.length() # current number of cols
for i, x in enumerate(zip(*headers[:header_lines]))
]
lines = lines[header_lines:] # in case of header_lines == 0
self._rowtype = namedlist('tsvobj', [c.name for c in self.columns])
self.recalc()
self.rows = []
with Progress(total=self.source.filesize) as prog:
for L in itertools.chain(lines, getlines(fp)):
row = L.split(delim)
ncols = self._rowtype.length() # current number of cols
if len(row) > ncols:
# add unnamed columns to the type not found in the header
newcols = [ColumnItem('', len(row)+i, width=8) for i in range(len(row)-ncols)]
self._rowtype = namedlist(self._rowtype.__name__, list(self._rowtype._fields) + ['_' for c in newcols])
for c in newcols:
self.addColumn(c)
elif len(row) < ncols:
# extend rows that are missing entries
row.extend([None]*(ncols-len(row)))
self.addRow(self._rowtype(row))
prog.addProgress(len(L))
from visidata import Sheet, ColumnItem, asyncthread, globalCommand, ENTER
import vgit
class GitGrep(vgit.GitSheet):
rowtype = 'results' # rowdef: list(file, line, line_contents)
columns = [
ColumnItem('filename', 0),
ColumnItem('linenum', 1),
ColumnItem('line', 2),
]
@asyncthread
def reload(self):
tmp = (self.topRowIndex, self.cursorRowIndex)
self.rows = []
for line in self.git_lines('grep', '--no-color', '-z', '--line-number', '--ignore-case', self.regex):
self.addRow(line.split('\0'))
self.topRowIndex, self.cursorRowIndex = tmp
Sheet.unbindkey('g/')
globalCommand('g/', 'git-grep', 'rex=input("git grep: "); vd.push(GitGrep(rex, regex=rex, source=sheet))', 'find in all files in this repo'),
GitGrep.addCommand(ENTER, 'dive-row', 'vs=GitFileSheet(cursorRow[0]); vs.cursorRowIndex=int(cursorRow[1])-1; vs.reload(); vd.push(vs)', 'go to this match')
statuslen = clipdraw(scr, vd.windowHeight-1, rightx, rstatus, attr, w=vs.windowWidth-1, rtl=True)
rightx -= statuslen
ret += statuslen
except Exception as e:
vd.exceptionCaught(e)
if scr:
curses.doupdate()
return ret
class StatusSheet(Sheet):
precious = False
rowtype = 'statuses' # rowdef: (priority, args, nrepeats)
columns = [
ColumnItem('priority', 0, type=int, width=0),
ColumnItem('nrepeats', 2, type=int, width=0),
ColumnItem('args', 1, width=0),
Column('message', getter=lambda col,row: composeStatus(row[1], row[2])),
]
colorizers = [
RowColorizer(1, 'color_error', lambda s,c,r,v: r and r[0] == 3),
RowColorizer(1, 'color_warning', lambda s,c,r,v: r and r[0] in [1,2]),
]
def reload(self):
self.rows = self.source
@VisiData.property
def statusHistorySheet(vd):
return StatusSheet("status_history", source=vd.statusHistory[::-1]) # in reverse order
def addRow(self, row, index=None):
super().addRow(row, index=index)
if isinstance(row, dict):
for k in row:
if k not in self.colnames:
c = ColumnItem(k, type=deduceType(row[k]))
self.colnames[k] = c
self.addColumn(c)
return row
def setCols(self, headerrows):
self.columns = []
for i, _ in enumerate(itertools.zip_longest(*headerrows)):
self.addColumn(ColumnItem('', i))
self.setColNames(headerrows)
self._rowtype = namedlist('tsvobj', [(c.name or '_') for c in self.columns])
option('visibility', 0, 'visibility level (0=low, 1=high)')
def getOptionsSheet(sheet):
optsheet = getattr(sheet, 'optionsSheet', None)
if not optsheet:
sheet.optionsSheet = OptionsSheet(sheet.name+"_options", source=sheet)
return sheet.optionsSheet
class StatusSheet(Sheet):
precious = False
rowtype = 'statuses' # rowdef: (priority, args, nrepeats)
columns = [
ColumnItem('priority', 0, type=int, width=0),
ColumnItem('nrepeats', 2, type=int, width=0),
ColumnItem('args', 1, width=0),
Column('message', getter=lambda col,row: composeStatus(row[1], row[2])),
]
colorizers = [
RowColorizer(1, 'color_error', lambda s,c,r,v: r and r[0] == 3),
RowColorizer(1, 'color_warning', lambda s,c,r,v: r and r[0] in [1,2]),
]
def reload(self):
self.rows = vd.statusHistory[::-1]
class ColumnsSheet(Sheet):
rowtype = 'columns'
_rowtype = Column
_coltype = ColumnAttr
def reload(self):
sheets = self.sources
# first item in joined row is the key tuple from the first sheet.
# first columns are the key columns from the first sheet, using its row (0)
self.columns = []
for i, c in enumerate(sheets[0].keyCols):
self.addColumn(SubrowColumn(c.name, ColumnItem(c.name, i, type=c.type, width=c.width), 0))
self.setKeys(self.columns)
for sheetnum, vs in enumerate(sheets):
# subsequent elements are the rows from each source, in order of the source sheets
ctr = collections.Counter(c.name for c in vs.nonKeyVisibleCols)
for c in vs.nonKeyVisibleCols:
newname = c.name if ctr[c.name] == 1 else '%s_%s' % (vs.name, c.name)
self.addColumn(SubrowColumn(newname, c, sheetnum+1))
rowsBySheetKey = {}
rowsByKey = {}
groupRowsByKey(sheets, rowsBySheetKey, rowsByKey)
self.rows = []