예제 #1
0
    def rm_cmd(self, argv):
        """usage: rm [-nv] <file>
 rm -R[-v] <file-or-directory>

- remove file or directory """
        # 指定するファイルを削除する。
        # ディレクトリも破棄対象とする場合は -R オプションを合わせて指定すること

        recursive = False
        dryrun = False
        args = []

        while argv:
            opts, params = cli.getopt(argv, 'Rnv', (
                'recursive',
                'verbose',
                'dryrun',
            ))
            for opt, optarg in opts:
                if opt in ('-R', '--recursive'): name = optarg
                elif opt in ('-n', '--dryrun'): dryrun = True
                elif opt in ('-v', '--verbose'): cli.verbose = 1
                else: return self.usage(cmd)

            argv = cli.nextopt(params, args)

        if not args: self.usage(cmd)
        return self._remove_reguler_files(args, recursive)
예제 #2
0
        def glob_cmd(self, line):
            """usage: glob [-d <base-dir>] pattern ..
- check glob pattern"""

            cmd = 'glob'
            argv = cli.split_line(line, useGlob=False)

            basedir = ''
            try:
                opts, args = cli.getopt(argv, 'd:')
            except cli.GetoptError:
                return self.usage(cmd)

            for opt, optarg in opts:
                if opt == '-d': basedir = optarg
                elif opt == '-v': verbose = True

            lf = LocalFolder(basedir)
            cli.puts(lf)

            entries = []
            for pat in args:
                entries.extend(lf.glob(pat))

            cli.show_items(entries)
예제 #3
0
    def lrmdir_cmd(self, argv):
        """usage: rmdir [-n][-p] <dir>
- remove empty directory (folder) """
        # ディレクトリを削除する
        cmd = argv.pop(0)
        opts, args = cli.getopt(argv, 'np', ('dryrun', 'parents', 'help'))
        dry_run = 0
        with_parent = 0
        mode = 0o777

        for opt, optarg in opts:
            if opt in ('-n', '--dryrun'): dry_run = 1
            elif opt in ('-p', '--parents'): with_parent = 1
            else: return self.usage(cmd)

        rc = 0
        for path in args:
            try:
                if with_parent:
                    os.removedirs(path)
                    continue
                os.rmdir(path)
            except OSError as e:
                log.error('%s while rmdir %s', path)
                rc = 1
예제 #4
0
    def cp_cmd(self, argv):
        """usage: cp [-pn] <src> <dst>
cp -R [-pn] <src> .. <dst-dir>

- copy file """
        # ファイルを複製する
        # 日付は維持する。
        # 複製途中のファイルは出現しないように調整する
        # 複数のファイルを指定した場合は、<dst>

        cmd = argv.pop(0)

        preserve = False
        recursive = False
        dryrun = False
        args = []

        while argv:
            opts, params = cli.getopt(argv, 'Rpnv', (
                'recursive',
                'preserve',
                'verbose',
                'dryrun',
            ))
            for opt, optarg in opts:
                if opt in ('-p', '--preserve'): preserve = True
                elif opt in ('-R', '--recursive'): recursive = True
                elif opt in ('-n', '--dryrun'): dryrun = True
                elif opt in ('-v', '--verbose'): cli.verbose = 1
                else: return self.usage(cmd)

            argv = cli.nextopt(params, args)

        if len(args) == 2 and not os.path.isdir(args[1]):
            self._copy_reguler_file(args[0], args[1], preserve)
            return 0

        dst_dir = args.pop(-1)
        if not os.path.isdir(dst_dir):
            log.error('%s is not directory.', dst_dir)
            return 1

        sum = 0
        ct = 0
        for fn in args:
            if os.path.isfile(fn):
                dst_file = os.path.join(dst_dir, os.path.basename(fn))
                sum += self._copy_reguler_file(fn, dst_file)
                ct += 1

            elif recursive and os.path.isdir(fn):
                dst_new = os.path.join(dst_dir, os.path.basename(fn))
                if not os.path.isdir(dst_new): os.makedirs(dst_new)
                mtime = os.path.getmtime(fn)
                bytes, nct = self._copy_folder(fn, dst_new, preserve=preserve)
                #os.utime(dst_new, (None, mtime))
                sum += bytes
                ct += nct
            else:
                log.error('%s not reguler file or directory', fn)
예제 #5
0
    def tsv_cmd(self, argv):
        """usage: tsv [-n <lines>][-s <skip>][-S <step>][-E <encoding>][-o <outfile>] files ..

options:
  -n #, --lines #
    読み込む総行数

  -s #, --skip #
    読み飛ばす行数。複数のファイルを指定する場合、最初のファイルについてのみ有効
"""

        # TSV/CSVファイルを読み込んで表示する
        cmd = argv[0]
        step = 1
        skip = 0
        lines = 0
        encoding = ''
        de = '\t'

        opts, args = cli.getopt(
            argv[1:], 'n:s:S:E:vd:',
            ('skip=', 'lines=', 'rows=', 'encoding=', 'step=', 'delimiter='))

        for opt, optarg in opts:
            if opt in ('-n', '--lines', '--rows'): lines = int(optarg)
            elif opt in ('-d', '--delimiter'): de = optarg
            elif opt in ('-s', '--skip'): skip = int(optarg)
            elif opt in ('-S', '--step'): step = int(optarg)
            elif opt in ('-E', '--encoding'): encoding = optarg
            elif opt == '-v': cli.verbose = True
            else: return self.usage(cmd, opt)

        if step <= 1:

            def xprint(ta):
                cli.puts(de.join(ta))
        else:

            def xprint(rows):
                for ta in rows:
                    cli.puts(de.join(ta))

        fm = LocalFolder()

        ct = 0
        for tf in args:
            for ta in fm.read_tsv_lines(tf,
                                        skip=skip,
                                        step=step,
                                        lines=lines,
                                        encoding=encoding):
                xprint(ta)
                ct += 1

        if cli.verbose:
            log.info('%d time repeat.', ct)
예제 #6
0
    def launcher_cmd(self, args):
        cmd = args.pop(0)

        op = 'run'
        opts, args = cli.getopt(argv, 'lv', ('list', 'verbose'))

        for opt, optarg in opts:
            if opt in ('-l', '--list'): op = 'list'
            elif opt == '-v': cli.verbose = True
            else: return self.usage(cmd, opt)
예제 #7
0
    def env_cmd(self, argv):
        "usage: env [-i][-u var] [name=value].. [cmd [args]] .."
        # 環境変数の確認とコマンドの実行
        cmd = argv[0]
        opts, args = cli.getopt(argv[1:], 'iu:v')

        from os import environ as ENV
        env = dict(ENV)

        for opt, optarg in opts:
            if opt == '-u':
                # 指定する変数を除外する
                if optarg in env: env.pop(optarg)
            elif opt == '-i':
                env.clear()
            elif opt == '-v':
                cli.verbose = True
            else:
                return self.usage(cmd)

        def show_env():
            for kn in sorted(env.keys()):
                cli.puts('%s=%s' % (kn, env[kn]))

        if not args: return show_env()

        ind = 0
        for tt in args:
            p = tt.find('=')
            if p < 1: break
            kn, kv = tt[:p], tt[p + 1:]
            env[kn] = kv
            ind += 1

        args = list(args[ind:])
        if not args: return show_env()

        wd = os.getcwd()

        # 標準入出力は、このプロセスのそれと同じものを利用する
        # コマンドの探索にはPATHを利用してくれる
        pc = subprocess.Popen(args, close_fds=True, cwd=wd, env=env)
        try:
            log.debug('pid: %d', pc.pid)
            rc = pc.wait()
        except:
            rc = 255
            pc.terminate()

        log.debug('rc: %d cmd: %s', rc, ' '.join(args))
        return rc
예제 #8
0
    def hostname_cmd(self, argv):
        'usage: hostname [-a]'
        cmd = argv.pop(0)
        show_all = False
        opts, args = cli.getopt(argv, 'a', ('all'))
        for opt, optarg in opts:
            if opt in ('-a', '--all'): show_all = True
            elif opt == '-v': cli.verbose = True
            else: return self.usage(cmd)

        uname = platform.uname()
        if show_all:
            cli.puts(uname)
            return
        cli.puts(uname[1])
예제 #9
0
    def find_cmd(self, line):
        """usage: find [-v][-t type][-d depth][-u user][-g group]\
        [-n include-pattern][-x exclude-pattern][-m +mod-date][-s +size] [directory] ..
- find directory entry"""
        # ディレクトリを探索して、条件に合致するファイルをレポートする
        cmd = 'find'
        argv = cli.split_line(line, useGlob=False)

        #print [ (idx,tt) for idx, tt in enumerate(argv) ]
        groups = []
        users = []
        depth = 10
        ftype = ''
        includes = []
        excludes = []
        pattern = []
        modtime = 0
        size = None
        args = []
        while argv:
            opts, params = cli.getopt(argv, 't:d:u:g:n:x:m:s:', (
                'group=',
                'user='******'depth=',
                'ftype=',
                'name=',
                'exclude=',
                'size=',
                'modified=',
            ))

            for opt, optarg in opts:
                if opt in ('-g', '--group'): groups.append(optarg)
                elif opt in ('-u', '--user'): users.append(optarg)
                elif opt in ('-d', '--depth'): depth = int(optarg)
                elif opt in ('-s', '--size'): size = int(size)
                elif opt in ('-n', '--name'): includes.append(optarg)
                elif opt in ('-x', '--exclude'): exclude.append(optarg)
                elif opt == '-v': cli.verbose = True

            argv = cli.nextopt(params, args)

        if not args: args.append('')

        for dirname in args:
            for fn in folder_walk(dirname):
                if fn.startswith('.'): continue
                cli.puts(fn)
예제 #10
0
    def lls_cmd(self, argv):
        "usage: lls <folder> .."
        cmd = argv[0]
        opts, args = cli.getopt(argv[1:], 'aldCvR')

        lsStyle = 'column'
        recursive = False
        ignoredir = False
        all = False

        for opt, optarg in opts:
            if opt == '-l': lsStyle = 'detail'
            elif opt == '-a': all = True
            elif opt == '-d': ignoredir = True
            elif opt == '-C': lsStyle = 'column'
            elif opt == '-R': recursive = True
            elif opt == '-v': cli.verbose = True
            else: return self.usage(cmd)

        detail = lsStyle == 'detail'
        if not args:
            return self._lls('', detail, recursive, all)

        ment = []

        if ignoredir:
            for ent in args:
                fmt, isdir = self._file_format(ent)
                if detail: cli.puts(fmt)
                else: ment.append(ent)

            if ment: cli.show_list(ment)
            return 0

        for ent in args:
            fmt, isdir = self._file_format(ent)
            if isdir:
                self._lls(ent, detail, recursive, all)
                continue

            if detail: cli.puts(fmt)
            else: ment.append(ent)

        if ment: cli.show_list(ment)
예제 #11
0
    def grep_cmd(self, line):
        """usage: grep [-invR][-e [RE]] [RE] <text-file> | <directory> ..
- print reguler expression match line """
        cmd = 'grep'
        argv = cli.split_line(line, useGlob=False)

        opts, args = cli.getopt(argv, 'invre:E:')

        recursive = False
        invert = False
        ignoreCase = False
        patterns = []
        lnumber = False
        encoding = 'utf-8'

        for opt, optarg in opts:
            if opt == '-i': ignoreCase = True
            elif opt == '-v': invert = True
            elif opt == '-R': recursive = True
            elif opt == '-n': lnumber = True
            elif opt == '-e': patterns.append(optarg)
            elif opt == '-E': encoding = optarg

        ind = 0
        al = len(args)
        if not al: return self.usage(cmd)

        if not patterns:
            patterns.append(args[ind])
            ind += 1

        if ind > al:
            log.error('empty search target')
            return

        if True:
            regexp = []
            reopts = 0
            if ignoreCase: reopts |= re.IGNORECASE

            for pat in patterns:
                regexp.append(re.compile(pat, reopts))

        def _grep_file(target):
            # パターンを検索してマッチしたら表示する
            with open(target) as fp:
                ct = 0
                line = fp.readline()
                try:
                    while line:
                        ct += 1
                        line = line.decode(encoding, 'replace')
                        #if ct < 3: print ct,':',type(line),line,

                        found = False
                        for reg in regexp:
                            if reg.search(line):
                                found = True
                                break

                        pflag = not invert if found else invert
                        if pflag:
                            if lnumber:
                                cli.puts('%s: %s: %s' % (target, ct, line),
                                         end='')
                            else:
                                cli.puts('%s: %s' % (target, line), end='')

                        line = fp.readline()
                except Exception as e:
                    cli.puts('ERROR: %s:%s:%s' % (tf, ct, e), file=cli.syserr)

            for tf in cli.glob(args[ind:]):
                _grep_file(tf)
예제 #12
0
    def lhead_cmd(self, argv):
        """usage: lhead [-n line][-s skip] <file>
- show head line of (gziped) file """
        # gzipファイルの先頭部を表示する
        cmd = argv.pop(0)

        lines = 10
        skip = 0
        encoding = None
        errors = 'strict'
        pattern = ''
        args = []
        while argv:
            opts, params = cli.getopt(argv, 'n:s:E:T',
                                      ('lines=', 'skip=', 'encoding=', 'help'))

            for opt, optarg in opts:
                if opt in ('-n', '--lines'): lines = int(optarg)
                elif opt in ('-s', '--skip'): skip = int(optarg)
                elif opt in ('-T', '--tsv'): pattern = r'\s+'
                elif opt in ('-P', '--pattern'): pattern = optarg
                elif opt in ('-E', '--encoding'): encoding = optarg
                else: return self.usage(cmd)

            argv = cli.nextopt(params, args)

        if len(args) == 0: return self.usage(cmd)

        lf = None
        for fn in args:
            basedir = os.path.dirname(fn)
            if not lf or lf.getFolderName() != basedir:
                lf = LocalFolder(basedir)

            fn0 = os.path.basename(fn)

            if not pattern:
                for line in lf.readlines(fn0,
                                         skip=skip,
                                         lines=lines,
                                         encoding=encoding,
                                         errors=errors):
                    cli.puts(line)
                return

            fs = re.compile(pattern)
            sep = '\t'

            for line in lf.readlines(fn0,
                                     skip=skip,
                                     lines=lines,
                                     encoding=encoding,
                                     errors=errors):
                ta = fs.split(line)
                cli.puts(sep.join(ta))

        @cli.alert
        def glob_cmd(self, line):
            """usage: glob [-d <base-dir>] pattern ..
- check glob pattern"""

            cmd = 'glob'
            argv = cli.split_line(line, useGlob=False)

            basedir = ''
            try:
                opts, args = cli.getopt(argv, 'd:')
            except cli.GetoptError:
                return self.usage(cmd)

            for opt, optarg in opts:
                if opt == '-d': basedir = optarg
                elif opt == '-v': verbose = True

            lf = LocalFolder(basedir)
            cli.puts(lf)

            entries = []
            for pat in args:
                entries.extend(lf.glob(pat))

            cli.show_items(entries)