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 BaseSheet, Sheet, Column, fail, confirm, CellColorizer, RowColorizer, asyncthread, options, saveSheets, inputPath, getDefaultSaveName, warning, status, Path, copy, Progress, option
option('color_add_pending', 'green', 'color for rows pending add')
option('color_change_pending', 'reverse yellow', 'color for cells pending modification')
option('color_delete_pending', 'red', 'color for rows pending delete')
# deferred cached
Sheet.init('_deferredAdds', dict) # [s.rowid(row)] -> row
Sheet.init('_deferredMods', dict) # [s.rowid(row)] -> (row, { [col] -> val })
Sheet.init('_deferredDels', dict) # [s.rowid(row)] -> row
Sheet.colorizers += [
CellColorizer(8, 'color_change_pending', lambda s,c,r,v: s.changed(c, r)),
RowColorizer(9, 'color_delete_pending', lambda s,c,r,v: s.rowid(r) in s._deferredDels),
RowColorizer(9, 'color_add_pending', lambda s,c,r,v: s.rowid(r) in s._deferredAdds),
]
@Sheet.api
def reset(self, *rows):
self._deferredAdds.clear()
self._deferredMods.clear()
self._deferredDels.clear()
import shlex
args = []
lmr = LazyMapRow(self.source, row)
for arg in shlex.split(self.expr):
if arg.startswith('$'):
args.append(str(lmr[arg[1:]]))
else:
args.append(arg)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p.communicate()
except Exception as e:
exceptionCaught(e)
class DirSheet(Sheet):
'Sheet displaying directory, using ENTER to open a particular file. Edited fields are applied to the filesystem.'
rowtype = 'files' # rowdef: Path
columns = [
DeferredSetColumn('directory',
getter=lambda col,row: row.parent.relpath(col.sheet.source.resolve()),
setter=lambda col,row,val: col.sheet.moveFile(row, val)),
DeferredSetColumn('filename',
getter=lambda col,row: row.name + row.ext,
setter=lambda col,row,val: col.sheet.renameFile(row, val)),
DeferredSetColumn('pathname', width=0,
getter=lambda col,row: row.resolve(),
setter=lambda col,row,val: os.rename(row.resolve(), val)),
Column('ext', getter=lambda col,row: row.is_dir() and '/' or row.suffix),
DeferredSetColumn('size', type=int,
getter=lambda col,row: row.stat().st_size,
setter=lambda col,row,val: os.truncate(row.resolve(), int(val))),
cmdparts = cmd.split()
if cmdparts[0] == 'git':
cmdparts = cmdparts[1:]
self.cmd = cmdparts + list(args)
def calcValue(self, r):
return list(vgit.git_lines('--git-dir', r.path.joinpath('.git'), *self.cmd))
class GitAllColumn(GitLinesColumn):
def calcValue(self, r):
return vgit.git_all('--git-dir', r.path.joinpath('.git'), *self.cmd).strip()
class GitOverview(Sheet):
rowtype = 'repos' # rowdef: GitRepo
columns = [
ColumnAttr('repo', 'path', type=str),
GitLinesColumn('stashes', 'git stash list', type=vlen),
GitLinesColumn('cached', 'git diff --cached', type=vlen),
GitLinesColumn('branches', 'git branch --no-color', type=vlen),
GitAllColumn('branch', 'git rev-parse --abbrev-ref HEAD'),
Column('modtime', type=date, getter=lambda c,r: modtime(r.path)),
]
nKeys = 1
@asyncthread
def reload(self):
import glob
import os.path
self.rows = []
if rowid not in col.sheet._deferredMods:
rowmods = {}
col.sheet._deferredMods[rowid] = (row, rowmods)
else:
_, rowmods = col.sheet._deferredMods[rowid]
rowmods[col] = val
else:
col._dm_setValue(row, val)
Sheet.addCommand('^S', 'commit-sheet', 'commit()')
unbindkey('g^S')
Sheet.bindkey('g^S', 'save-sheet')
BaseSheet.addCommand('^R', 'reload-sheet', '_dm_reload(); recalc(); status("reloaded")'),
Sheet.addCommand('z^R', 'reload-row', 'undoMod(cursorRow)')
Sheet.addCommand('z^R', 'reload-row', 'undoMod(cursorRow)')
Sheet.addCommand('gz^R', 'reload-rows', 'for r in selectedRows: undoMod(r)')
JoinSheet.trackmods = False
vd.cmdlog.trackmods = False
ColumnsSheet.trackmods = False
OptionsSheet.trackmods = False
PivotSheet.trackmods = False
IndexSheet.trackmods = False
MeltedSheet.trackmods = False
TransposeSheet.trackmods = False
Sheet.addCommand('d', 'delete-row', 'vd.cliprows = [(sheet, cursorRowIndex, deleteRows([cursorRow]))]; not sheet.defermods or cursorDown(1)')
from copy import copy
import shutil
import subprocess
import sys
import tempfile
import functools
from visidata import vd, asyncthread, sync, status, fail, option, options
from visidata import Sheet, saveSheets
vd.cliprows = [] # list of (source_sheet, source_row_idx, source_row)
vd.clipcells = [] # list of strings
Sheet.addCommand('y', 'copy-row', 'vd.cliprows = [(sheet, cursorRowIndex, cursorRow)]')
Sheet.addCommand('d', 'delete-row', 'vd.cliprows = [(sheet, cursorRowIndex, rows.pop(cursorRowIndex))]')
Sheet.addCommand('p', 'paste-after', 'rows[cursorRowIndex+1:cursorRowIndex+1] = list(deepcopy(r) for s,i,r in vd.cliprows)')
Sheet.addCommand('P', 'paste-before', 'rows[cursorRowIndex:cursorRowIndex] = list(deepcopy(r) for s,i,r in vd.cliprows)')
Sheet.addCommand('gd', 'delete-selected', 'vd.cliprows = list((None, i, r) for i, r in enumerate(selectedRows)); deleteSelected()')
Sheet.addCommand('gy', 'copy-selected', 'vd.cliprows = list((None, i, r) for i, r in enumerate(selectedRows)); status("%d %s to clipboard" % (len(vd.cliprows), rowtype))')
Sheet.addCommand('zy', 'copy-cell', 'vd.clipcells = [cursorDisplay]')
Sheet.addCommand('zp', 'paste-cell', 'cursorCol.setValuesTyped([cursorRow], vd.clipcells[0])')
Sheet.addCommand('zd', 'delete-cell', 'vd.clipcells = [cursorDisplay]; cursorCol.setValues([cursorRow], None)')
Sheet.addCommand('gzd', 'delete-cells', 'vd.clipcells = list(sheet.cursorCol.getDisplayValue(r) for r in selectedRows); cursorCol.setValues(selectedRows, None)')
Sheet.addCommand('gzy', 'copy-cells', 'vd.clipcells = [sheet.cursorCol.getDisplayValue(r) for r in selectedRows]; status("%d values to clipboard" % len(vd.clipcells))')
Sheet.addCommand('gzp', 'paste-cells', 'for r, v in zip(selectedRows or rows, itertools.cycle(vd.clipcells)): cursorCol.setValuesTyped([r], v)')
Sheet.addCommand('Y', 'syscopy-row', 'saveToClipboard(sheet, [cursorRow], input("copy current row to system clipboard as filetype: ", value=options.save_filetype))')
def _deferredAdds(sheet):
return dict() # [s.rowid(row)] -> row
@Sheet.lazy_property
def _deferredMods(sheet):
return dict() # [s.rowid(row)] -> (row, { [col] -> val })
@Sheet.lazy_property
def _deferredDels(sheet):
return dict() # [s.rowid(row)] -> row
theme('color_add_pending', 'green', 'color for rows pending add')
theme('color_change_pending', 'reverse yellow', 'color for cells pending modification')
theme('color_delete_pending', 'red', 'color for rows pending delete')
Sheet.colorizers += [
CellColorizer(8, 'color_change_pending', lambda s,c,r,v: s.changed(c, r)),
RowColorizer(9, 'color_delete_pending', lambda s,c,r,v: s.rowid(r) in s._deferredDels),
RowColorizer(9, 'color_add_pending', lambda s,c,r,v: s.rowid(r) in s._deferredAdds),
]
@Sheet.api
def _dm_reset(sheet, *rows):
sheet._deferredAdds.clear()
sheet._deferredMods.clear()
sheet._deferredDels.clear()
@BaseSheet.api
def _dm_reload(sheet):
sheet._dm_reset()
globalCommand('zO', 'options-sheet', 'vd.push(getOptionsSheet(sheet)).reload()')
globalCommand('O', 'options-global', 'vd.push(vd.optionsSheet)')
Sheet.addCommand('C', 'columns-sheet', 'vd.push(ColumnsSheet(name+"_columns", source=[sheet]))')
globalCommand('z^H', 'help-commands', 'vd.push(HelpSheet(name + "_commands", source=sheet, revbinds={}))')
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]
'''slide rows/columns around'''
from visidata import Sheet, moveListItem, globalCommand
Sheet.addCommand('H', 'slide-left', 'i = sheet.cursorVisibleColIndex; sheet.cursorVisibleColIndex = moveVisibleCol(sheet, i, i-1)')
Sheet.addCommand('L', 'slide-right', 'i = sheet.cursorVisibleColIndex; sheet.cursorVisibleColIndex = moveVisibleCol(sheet, i, i+1)')
Sheet.addCommand('J', 'slide-down', 'i = sheet.cursorRowIndex; sheet.cursorRowIndex = moveListItem(rows, i, i+1)')
Sheet.addCommand('K', 'slide-up', 'i = sheet.cursorRowIndex; sheet.cursorRowIndex = moveListItem(rows, i, i-1)')
Sheet.addCommand('gH', 'slide-leftmost', 'columns.insert(0, columns.pop(cursorColIndex))')
Sheet.addCommand('gL', 'slide-rightmost', 'columns.append(columns.pop(cursorColIndex))')
Sheet.addCommand('gJ', 'slide-bottom', 'rows.append(rows.pop(cursorRowIndex))')
Sheet.addCommand('gK', 'slide-top', 'rows.insert(0, rows.pop(cursorRowIndex))')
Sheet.addCommand('zH', 'slide-left-n', 'i = sheet.cursorVisibleColIndex; n=int(input("slide col left n=", value=1)); sheet.cursorVisibleColIndex = moveVisibleCol(sheet, i, i-n)')
Sheet.addCommand('zL', 'slide-right-n', 'i = sheet.cursorVisibleColIndex; n=int(input("slide col right n=", value=1)); sheet.cursorVisibleColIndex = moveVisibleCol(sheet, i, i+n)')
Sheet.addCommand('zJ', 'slide-down-n', 'i = sheet.cursorRowIndex; n=int(input("slide row down n=", value=1)); sheet.cursorRowIndex = moveListItem(rows, i, i+n)')
Sheet.addCommand('zK', 'slide-up-n', 'i = sheet.cursorRowIndex; n=int(input("slide row up n=", value=1)); sheet.cursorRowIndex = moveListItem(rows, i, i-n)')
def moveVisibleCol(sheet, fromVisColIdx, toVisColIdx):
'Move visible column to another visible index in sheet.'
toVisColIdx = min(max(toVisColIdx, 0), sheet.nVisibleCols)
fromColIdx = sheet.columns.index(sheet.visibleCols[fromVisColIdx])
toColIdx = sheet.columns.index(sheet.visibleCols[toVisColIdx])
moveListItem(sheet.columns, fromColIdx, toColIdx)
return toVisColIdx
def setDiffSheet(vs):
Sheet.colorizers.append(CellColorizer(8, None, makeDiffColorizer(vs)))
def newRow(self):
return Sheet('', columns=[ColumnItem('', 0)], rows=[])