Пример #1
0
def list_installed():
    cmd = Command("pacman", ["-Qe"], opts=ExecOpts(display=False))
    cmd.safe_run()
    if cmd.stdout:
        return [line.split(" ")[0] for line in cmd.stdout.split("\n")]
    else:
        return []
Пример #2
0
def lvm_backup(vg: str, lv: str, out_p: Path, verbose: bool = True) -> Path:
    """Creates a snapshot of a logical volume, mounts it in temporary directory
    creates an tar gzip archive in out_path and cleans up the snapshot afterwards.
    Returns a path to final archive containing backed up files."""
    opts = ExecOpts(quit=True, collect=False)
    system.install_pkg_if_bin_not_exists("tar")
    system.install_pkg_if_bin_not_exists("pigz")
    try:
        snapshot = lvm_snapshot(vg, lv, opts=opts)
        out_p = out_p / (snapshot + ".tgz")

        with TemporaryDirectory() as tempdir:
            inp_p = Path(tempdir) / snapshot
            inp_p.mkdir(parents=True)
            try:
                Command("mount", [f"/dev/{vg}/{snapshot}",
                                  str(inp_p)],
                        opts=opts).safe_run()
                flags = "-cvf" if verbose else "-cf"
                bash(
                    f"cd {str(inp_p)} && tar -I pigz {flags} {str(out_p)} ./*",
                    quit=True,
                )
            finally:
                Command("umount", [f"/dev/{vg}/{snapshot}"],
                        opts=opts).safe_run()
    finally:
        if "snapshot" in locals():
            lvm_remove(vg, snapshot)

    return out_p
Пример #3
0
    def install_nvim_plugins(self):
        system.install_pkg_if_bin_not_exists("nvim", pkg="neovim")
        self.install_vim_plug()
        p = self.xdg_conf_dir().joinpath("/nvim/init.vim")
        if Path(p).exists():
            system.nvim("PlugInstall|q|q")
        else:
            eprint(f"Missing nvim config file at {p}")

        system.install_pkg_if_bin_not_exists("pip2", "python2-pip")
        system.install_pkg_if_bin_not_exists("pip", "python-pip")
        Command("pip", ["install", "neovim"]).safe_run()
        Command("pip2", ["install", "neovim"]).safe_run()
Пример #4
0
def build_agent_demos(args):
    """sdk-agent适配各个渠道的demo,一锅出多个Android apk和适配层类库
	python apk_builder.py -c demo -s demo.ini -ch tencent
	"""
    Command.set_log_level(logging.DEBUG)
    builder = AgentBuilder(args.src, args.dry_run)
    builder.init()

    builder.build_baselib()

    builder.build_channel_apks(args.channel)

    logging.info('==== Build %d channels ====\n' % len(builder.build_info) +
                 '\n'.join(builder.build_info))
Пример #5
0
def lvm_size(vg: str, lv: str, opts: ExecOpts = DEFAULT_OPTS) -> int:
    """Returns size in bytes of a given logical volume"""
    cmd = Command(
        "lvs",
        [
            f"{vg}/{lv}", "-o", "LV_SIZE", "--noheadings", "--units", "B",
            "--nosuffix"
        ],
        opts=opts,
    )
    cmd.safe_run()
    if cmd.exit_code == 0 and cmd.stdout:
        return int(cmd.stdout.strip())

    return 0
Пример #6
0
def test():
    """
	"""
    my_labels = 'first step; second step; third step; forth step'.split(';')
    try:
        print 'begin merge...'
        Command.merge_img(src_img='j_[1-4].jpg',
                          width=300,
                          caption='做一个测试',
                          labels=my_labels,
                          clean=False)
        print 'merge over.'
    except Exception, e:
        print 'except:', e
        raise
Пример #7
0
 def install_grub(self):
     system.install_pkgs(["grub", "efibootmgr"],
                         pkgmngr="paru",
                         user=self.username)
     location = inp("Enter boot partition location: ")
     if location:
         Command(
             "grub-install",
             [
                 "--target=x86_64-efi",
                 f"--efi-directory={location}",
                 "--bootloader-id=GRUB",
             ],
         ).safe_run()
         Command("grub-mkconfig",
                 ["-o", f"{location}/grub/grub.cfg"]).safe_run()
Пример #8
0
def gen_locale(locales: List[str]):
    with open("/etc/locale.gen", "a+") as f:
        for line in f.readlines():
            for locale in locales:
                if line.startswith(f"#{locale}"):
                    line = locale

    Command("locale-gen", []).safe_run()
Пример #9
0
def lvm_snapshot(vg: str, lv: str, opts: ExecOpts = DEFAULT_OPTS) -> str:
    """Creates a snapshot of a given logical volume"""
    size = lvm_size(vg, lv, ExecOpts(quit=True))
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    name = f"{vg}-{lv}_snapshot_{timestamp}"
    Command("lvcreate",
            ["-L", str(size) + "B", "-s", "-n", name, f"{vg}/{lv}"],
            opts=opts).safe_run()
    return name
Пример #10
0
def extar(f: Path, to: Path):
    Command(
        "tar",
        [
            "--extract",
            f"--file={str(f)}",
            f"--directory={str(to)}",
        ],
    ).safe_run()
Пример #11
0
    def mainloop(self, thread_id, sock_c, addr_c):
        debug('Serve new client', thread_id, addr_c)
        self.x.client = ClientState(thread_id, sock=sock_c, addr=addr_c)
        while True:
            cmdstr = self.x.client.sock.recv(u.buflen)
            cmd = Command.from_str(cmdstr)
            debug(cmd)

            self.handler_map[cmd.verb](cmd)
Пример #12
0
    def install_themes(self):
        if Path(self.theme_dir()).exists():
            shutil.rmtree(self.theme_dir())

        os.makedirs(self.theme_dir())

        git_theme_dir = self.git_conf_dir() / "themes"
        system.extar(git_theme_dir / "Sweet-Dark.tar.xz", self.theme_dir())
        system.extar(git_theme_dir / "Sweet-Purple.tar.xz", self.theme_dir())
        system.extar(git_theme_dir / "Sweet-Teal.tar.xz", self.theme_dir())

        Command(
            "unzip",
            [
                str(git_theme_dir / "Solarized-Dark-Orange_2.0.1.zip"),
                "-d",
                str(self.theme_dir()),
            ],
        ).safe_run()
        system.gitclone(f"{REPO_BASE}/gruvbox-gtk",
                        self.theme_dir() / "gruvbox-gtk")
        system.gitclone(f"{REPO_BASE}/Aritim-Dark",
                        self.theme_dir() / "aritim")
        system.gitclone("https://github.com/Dracula/gtk",
                        self.theme_dir() / "Dracula")

        try:
            Command(
                "mv",
                [
                    str(self.theme_dir() / "aritim/GTK"),
                    str(self.theme_dir() / "Aritim-Dark"),
                ],
            ).safe_run()
        finally:
            shutil.rmtree(str(self.theme_dir() / "aritim"))

        system.cp(self.theme_dir() / "Dracula",
                  Path("/usr/share/themes/Dracula"))
        system.cp(self.theme_dir() / "gruvbox-gtk",
                  Path("/usr/share/themes/gruvbox-gtk"))
        system.cp(self.theme_dir() / "Aritim-Dark",
                  Path("/usr/share/themes/Aritim-Dark"))
Пример #13
0
def create_user(user: str, password=""):
    args = [
        "--groups",
        "wheel",
        "--create-home",
        "--shell",
        "/bin/bash",
    ]

    if password:
        args += ["--password", password]

    Command(
        "useradd",
        args + [user],
        opts=ExecOpts(quit=True),
    ).safe_run()

    if not password:
        Command("passwd", [user], opts=ExecOpts(redirect=True,
                                                follow=False)).safe_run()
Пример #14
0
def container_start(name, quota, period, program):
    cmd = [
        "lxc-execute",
        "-n",
        name,
        "-s",
        "lxc.cgroup.cpuset.cpus=0",
        "-s",
        "lxc.cgroup.cpu.cfs_quota_us=%d" % quota,
        "-s",
        "lxc.cgroup.cpu.cfs_period_us=%d" % period,
    ] + program.split(' ')

    return Command(cmd).read_full()
Пример #15
0
def read_version_from_project():
    """read get version command from a file,
	excute command to get local project's version
	"""
    try:
        # grep MyEditionId ../MyServiceDefine.h |cut -d "\\"" -f 2
        version_cmd = open('version_cmd').readline().strip()
        # log stdout
        (cost, out, err) = Command.excute(version_cmd, stdout=True)
        if len(err) > 0:
            print version_cmd, '\nerr: ', err

        return out.strip('\n')
    except:
        return 'unknown'
Пример #16
0
 def insertRadios(self, row):
     radioFrame = Frame(row.line)
     radioFrame.grid(row=0, column=0)
     currCol = 0
     radios = []
     v = row.selection
     ci = 0
     colours = row.defaultColours()
     pools = self.guesser.poolNames()
     for pool in pools:
         rb = Radiobutton(radioFrame, text=pool, variable=v, value=pool, command=Command(self.training, row), bg=None)
         rb.grid(row=0, column=currCol)
         radios.append(rb)
         currCol += 1
         ci += 1
     row.radios = radios
Пример #17
0
def build_xcode_project(args):
    """调用方法: python ~/apk-builder/xcode_builder.py -a ipa --ipa SDK_V5 -p FLGamePlatformDemo -s FLGamePlatformDemoRelease --clean
工作步骤:
	1. XCode项目打包
	2. 重命名ipa为 %(ipa_name)s_v%(code_ver)s_r%(repo_ver)s_b%(build_num)s.ipa
	例如: SDK_V5_v5.1.56_r168988_b62.jar
	3. create ota plist
	"""
    # 1. build xcode project and export ipa
    Command.xcodebuild_ipa(project=args.project + '.xcodeproj',
                           scheme=args.scheme,
                           export=args.export,
                           plist=args.plist,
                           is_clean=args.clean,
                           dry_run=args.dry_run)
    print 'ipa file name:', args.ipa_name

    # 2. rename
    ipa_name = '%(ipa_name)s_v%(code_ver)s_r%(repo_ver)s_b%(build_num)s.ipa' % {
        'ipa_name':
        args.ipa_name,
        'code_ver':
        read_version_from_project(),
        'repo_ver':
        Command.git_ver('..', do_update=False)
        if args.git else Command.svn_ver('..', do_update=False),
        'build_num':
        os.environ.get('BUILD_NUMBER')
    }
    rename_cmd = 'mv %(export_path)s/%(scheme_name)s.ipa %(export_path)s/%(ipa_name)s' % {
        'scheme_name': args.scheme,
        'export_path': args.export,
        'ipa_name': ipa_name
    }
    (cost, out, err) = Command.excute(rename_cmd, args.dry_run)
    if len(err) == 0:
        logging.info('mission done for building [%s]' % ipa_name)
    else:
        logging.error('mission failed for building [%s]' % ipa_name)
    # 3. create ota plist
    # cp ipa to nginx root path
    rename_cmd = 'cp %(export_path)s/%(ipa_name)s %(root_path)s' % {
        'export_path': args.export,
        'ipa_name': ipa_name,
        'root_path': args.root_path
    }
    (cost, out, err) = Command.excute(rename_cmd, args.dry_run)

    plistBuddy = PlistBuddy(args.root_path, ipa_name)
    # create plist
    plistBuddy.create_ota_plist(os.path.join(args.ipa_url, ipa_name),
                                os.path.join(args.ipa_url, 'icon.png'))
    # create update links to plist
    plistBuddy.update_index_html(args.ipa_name, args.ipa_url)
Пример #18
0
def install_pkgs(pkgs: List[str], pkgmngr="/usr/bin/pacman", user="******"):
    Command("sudo",
            ["-u", user, pkgmngr, "--sync", "--noconfirm"] + pkgs).safe_run()
Пример #19
0
    def p_statement(self, p):
        'statement : WORD SPACE args'
        p[0] = Command(p[1], *p[3])

        print 'p_statement: %s' % list(p)
Пример #20
0
def link_impl(f: Path, to: Path):
    Command(
        "ln",
        ["--symbolic", "--force", "--verbose",
         str(f), str(to)],
    ).safe_run()
Пример #21
0
 def arch_chroot(self, cmd: str):
     Command(
         "/usr/bin/arch-chroot",
         [self.location, "/bin/bash", "-c", cmd],
         opts=ExecOpts(quit=True, redirect=True, follow=False),
     ).safe_run(reraise=False)
Пример #22
0
def nvim(cmd: str):
    Command("nvim", ["--headless", "-c", f'"{cmd}"']).safe_run()
Пример #23
0
def gitclone(repo: str, where=Path("")):
    p = str(where)
    install_pkg_if_bin_not_exists("git")
    Command("git", ["clone", repo, p] if p else ["clone", repo]).safe_run()
Пример #24
0
def cp(f1: Path, f2: Path):
    Command("cp", ["--verbose", str(f1), str(f2)]).safe_run()
Пример #25
0
def chown(p: Path, user: str, group: str, recursive=True):
    Command(
        "chown",
        ["-R", f"{user}:{group}", str(p)]
        if recursive else [f"{user}:{group}", str(p)],
    ).safe_run()
Пример #26
0
def chmod(flags: str, f: Path):
    Command("chmod", [flags, "--verbose", str(f)]).safe_run()
Пример #27
0
def systemctl_enable(service: str):
    Command("systemctl", ["enable", service]).safe_run()
Пример #28
0
 def mkinitram(self):
     Command("mkinitcpio", ["-P"]).safe_run()
Пример #29
0
def install_and_run_reflector():
    install_pkg_if_bin_not_exists("reflector")
    Command(
        "reflector",
        ["-l", "100", "--sort", "rate", "--save", "/etc/pacman.d/mirrorlist"],
    ).safe_run()
Пример #30
0
def lvm_remove(vg: str, lv: str, opts: ExecOpts = DEFAULT_OPTS):
    """Removes a logical volume"""
    Command("lvremove", ["-y", f"{vg}/{lv}"], opts=opts).safe_run()