Răsfoiți Sursa

Add trashscript

Kevin Heinicke 5 ani în urmă
părinte
comite
56247c56e2
8 a modificat fișierele cu 63 adăugiri și 71 ștergeri
  1. 1 1
      gitignore_global
  2. 1 0
      install.conf.yaml
  3. 1 0
      nvim/UltiSnips/python.snippets
  4. 1 0
      nvimrc
  5. 0 49
      scripts/syncIgnore
  6. 55 18
      scripts/trash
  7. 1 0
      tmux.conf
  8. 3 3
      zsh_local_e5

+ 1 - 1
gitignore_global

@@ -35,7 +35,7 @@
 .Trashes
 ehthumbs.db
 Thumbs.db
-.ipynb_checkpoints
+.ipynb_checkpoints/
 
 # Development remnants #
 ########################

+ 1 - 0
install.conf.yaml

@@ -29,3 +29,4 @@
     ~/.gitignore_global: gitignore_global
     ~/.taskrc: taskrc
     ~/.p10k.zsh: p10k.zsh
+    ~/.local/bin/trash: scripts/trash

+ 1 - 0
nvim/UltiSnips/python.snippets

@@ -3,6 +3,7 @@ snippet main
 def main():
 	${1}
 
+
 if __name__ == '__main__':
 	main()
 endsnippet

+ 1 - 0
nvimrc

@@ -8,6 +8,7 @@ Plug 'scrooloose/nerdtree'
 Plug 'Xuyuanp/nerdtree-git-plugin'
 Plug 'tpope/vim-fugitive'
 Plug 'airblade/vim-gitgutter'
+Plug 'whiteinge/diffconflicts'
 Plug 'mhinz/vim-startify'
 Plug 'altercation/vim-colors-solarized'
 Plug 'vim-airline/vim-airline'

+ 0 - 49
scripts/syncIgnore

@@ -1,49 +0,0 @@
-#! /usr/bin/env python3
-import sys
-import os
-
-currentDir = os.getcwd()
-
-BEGIN = '#$ IGNORE'
-END = '#$ END IGNORE'
-
-while not os.path.isfile(os.path.join(currentDir, '.sync/IgnoreList')):
-    currentDir = os.path.abspath(os.path.join(currentDir, '..'))
-    if currentDir == os.path.realpath('/'):
-        print('Error: Did not find `.sync`-directory above current directory.')
-        sys.exit(1)
-
-with open(os.path.join(currentDir, '.sync/IgnoreList'), 'r') as f:
-    lineArray = f.read().split('\n')
-
-try:
-    before = lineArray[:lineArray.index(BEGIN)]
-    after = lineArray[lineArray.index(END) + 1:]
-except:
-    before = lineArray
-    after = ['']
-
-
-def findRepos(directory, repoArray=[]):
-    for file in os.listdir(directory):
-        if file.endswith('.syncignore'):
-            repoArray.append(directory)
-        elif os.path.isdir(os.path.join(directory, file)):
-            findRepos(os.path.join(directory, file), repoArray)
-        elif file.startswith('.'):
-            pass
-    return repoArray
-
-newIgnored = findRepos(currentDir)
-if len(newIgnored) == 0:
-    print('Found no `.syncignore`-files.')
-    sys.exit(0)
-
-for index, string in enumerate(newIgnored):
-    newIgnored[index] = os.path.join('.', string.replace(currentDir, ''))
-print("Ignoring\n.", '\n.'.join(newIgnored))
-newIgnored.insert(0, BEGIN)
-newIgnored.append(END)
-
-with open(os.path.join(currentDir, '.sync/IgnoreList'), 'w') as f:
-    f.write('\n'.join(before + newIgnored + after))

+ 55 - 18
scripts/trash

@@ -1,4 +1,7 @@
 #! /usr/bin/env python3
+""" Move files and directories to custom trash directories, taking the
+corresponding mount points into account.
+"""
 
 from pathlib import Path
 import argparse
@@ -6,7 +9,7 @@ import logging
 import sys
 import os
 import json
-
+from datetime import datetime
 
 DEFAULT_CONFIG = {
     'trashes': [
@@ -16,8 +19,10 @@ DEFAULT_CONFIG = {
 
 
 def parse_args():
-    parser = argparse.ArgumentParser()
-    parser.add_argument('names', nargs='+')
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument('names', nargs='*')
+    parser.add_argument('-d', '--dry-run', action='store_true')
+    parser.add_argument('-l', '--list', action='store_true')
     return parser.parse_args()
 
 
@@ -29,7 +34,7 @@ def lowest_mount(path: Path) -> Path:
     return path
 
 
-def getconfig():
+def getconfig() -> dict:
     config_file = Path('~/.config/trash.json').expanduser()
     config = DEFAULT_CONFIG
     if config_file.is_file():
@@ -38,22 +43,16 @@ def getconfig():
     return config
 
 
-def main():
-    args = parse_args()
-    logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
-
-    config = getconfig()
-    logging.debug(config)
-
-    trashes = []
+def get_trashes(config):
+    trashes: list[Path] = []
     for trashdir in config['trashes']:
         trashdir = Path(os.path.expandvars(trashdir)).expanduser().resolve()
-        if not trashdir.is_dir():
-            logging.info(f'new trash created at {trashdir}.')
-            trashdir.mkdir()
         trashes.append(trashdir)
+    return trashes
+
 
-    for name in args.names:
+def trash(names, config, dry_run=False):
+    for name in names:
         name = Path(os.path.expandvars(name))
 
         if not (name.is_file() or name.is_dir()):
@@ -63,10 +62,16 @@ def main():
         name = name.absolute()
 
         trashed = False
-        for trashdir in trashes:
+        for trashdir in get_trashes(config):
             try:
                 if lowest_mount(trashdir) == lowest_mount(name):
-                    logging.info(f'Will move {name} to {trashdir}')
+                    newname = (trashdir / datetime.now().isoformat(
+                        timespec='seconds').replace(':', '_') /
+                               '/'.join(name.parts[1:]))
+                    newname.parent.mkdir(parents=True, exist_ok=True)
+                    logging.debug(f'Will move {name} to {newname}')
+                    if not dry_run:
+                        name.rename(newname)
                     trashed = True
                     break
             except ValueError:
@@ -76,5 +81,37 @@ def main():
             logging.warning(f'Unable to trash {name}')
 
 
+def trashed_sort_key(trashed_path: Path) -> int:
+    # length of the used ISO format is 19!
+    date_string = trashed_path.parts[-1][-19:].replace('_', ':')
+    logging.debug(f'Extracted {date_string} from {trashed_path}')
+    return datetime.fromisoformat(date_string).timestamp()
+
+
+def list_trashed(config):
+    """ Yield trashed entries for trashdirs of given config
+    """
+    for trashdir in get_trashes(config):
+        for entry in sorted(trashdir.iterdir(), key=trashed_sort_key):
+            yield entry
+
+
+def main():
+    args = parse_args()
+    logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
+
+    config = getconfig()
+    logging.debug(config)
+
+    if args.list:
+        print(*list(list_trashed(config)), sep='\n')
+        sys.exit()
+
+    trash(args.names, config, dry_run=args.dry_run)
+
+    if args.dry_run:
+        logging.info('Dry run. Nothin happened. I guess.')
+
+
 if __name__ == '__main__':
     main()

+ 1 - 0
tmux.conf

@@ -1,6 +1,7 @@
 # List of plugins
 set -g @plugin 'tmux-plugins/tpm'
 set -g @plugin 'tmux-plugins/tmux-sensible'
+set -g @plugin 'tmux-plugins/tmux-resurrect'
 set -g @plugin 'christoomey/vim-tmux-navigator'
 set -g @plugin 'tmux-plugins/tmux-yank'
 

+ 3 - 3
zsh_local_e5

@@ -7,12 +7,12 @@ export KRB5CCNAME=$HOME/.krb5cc
 export LIBCLANG_PATH=/cvmfs/sft.cern.ch/lcg/releases/clang/8.0.0-ed577/x86_64-centos7/lib/libclang.so
 export CLANG_HEADER=/cvmfs/sft.cern.ch/lcg/releases/clang/8.0.0-ed577/x86_64-centos7/lib/clang/8.0.0/include
 export D=/ceph/users/kheinicke/b2oc/dsk-run2
-export UDIR=/ceph/users/kheinicke/Urania
+export UDIR=/home/kheinicke/repos/Urania
 export B=$UDIR/PhysFit/B2DXFitters
 export BC=$UDIR/PhysFit/B2DXFitters/data/Bs2DsK_Run2CPV/Bs2DsPi
-export HOME2=/net/nfshome2/home/kheinicke
+export HOME2=/net/nfshome/home/kheinicke
 
-alias upy="/ceph/users/kheinicke/Urania/build.x86_64-centos7-gcc9-opt/run python"
+alias upy="$UDIR/build.x86_64-centos7-gcc9-opt/run python"
 alias set_conda="source /usr/scripts/set_conda.sh && source ~/.set_conda_local"
 
 function ipy () {