Skip to content

Commit

Permalink
update tools
Browse files Browse the repository at this point in the history
  • Loading branch information
ice-black-tea committed Aug 18, 2024
1 parent fb62797 commit 0d23608
Show file tree
Hide file tree
Showing 6 changed files with 155 additions and 34 deletions.
9 changes: 5 additions & 4 deletions src/linktools/_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ def config(self) -> dict:

if not utils.is_empty(cmdline):
cmdline = shutil.which(cmdline)
if not utils.is_empty(cmdline):
if not utils.is_empty(cmdline) and cmdline != str(self.stub):
config["absolute_path"] = cmdline
config["executable_cmdline"] = [cmdline]
else:
Expand Down Expand Up @@ -383,17 +383,18 @@ def prepare(self) -> None:
shutil.move(temp_path, self.absolute_path)

if not os.access(self.stub, os.X_OK):
from linktools.cli.commands.common import tools as cmd
from linktools.cli import stub
self._tools.logger.debug(f"Create stub {self.stub}")
self.stub.parent.mkdir(parents=True, exist_ok=True)
cmdline = utils.list2cmdline([sys.executable, "-m", stub.__name__, "tool", self.name])
if utils.get_system() == "windows":
with open(self.stub, "wt") as fd:
fd.write(f"@echo off\n")
fd.write(f"{sys.executable} -m {cmd.__name__} --set cmdline='' {self.name} %*\n")
fd.write(f"{cmdline} %*\n")
else:
with open(self.stub, "wt") as fd:
fd.write(f"#!{shutil.which('sh')}\n")
fd.write(f"{sys.executable} -m {cmd.__name__} --set cmdline='' {self.name} $@\n")
fd.write(f"{cmdline} $@\n")
os.chmod(self.stub, 0o0755)

# change tool file mode
Expand Down
57 changes: 57 additions & 0 deletions src/linktools/cli/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@author : Hu Ji
@file : __main__.py.py
@time : 2024/8/8 17:34
@site : https://github.com/ice-black-tea
@software: PyCharm
,----------------, ,---------,
,-----------------------, ," ,"|
," ,"| ," ," |
+-----------------------+ | ," ," |
| .-----------------. | | +---------+ |
| | | | | | -==----'| |
| | $ sudo rm -rf / | | | | | |
| | | | |/----|`---= | |
| | | | | ,/|==== ooo | ;
| | | | | // |(((( [33]| ,"
| `-----------------' |," .;'| |(((( | ,"
+-----------------------+ ;; | | |,"
/_)______________(_/ //' | +---------+
___________________________/___ `,
/ oooooooooooooooo .o. oooo /, `,"-----------
/ ==ooooooooooooooo==.o. ooo= // ,``--{)B ,"
/_==__==========__==_ooo__ooo=_/' /___________,"
"""

import sys

from ..types import Error

if __name__ == '__main__':

index = 1

if len(sys.argv) <= index:
raise Error("Invalid arguments: missing type")
type = sys.argv[index]
index += 1

if type == "tool":
from linktools import environ

if len(sys.argv) <= index:
raise Error("Invalid arguments: missing name")
name = sys.argv[index]
index += 1

exit(
environ.get_tool(name, cmdline=None)
.popen(*sys.argv[index:])
.call()
)

raise Error(f"Invalid arguments: unknown type `{type}`")
12 changes: 4 additions & 8 deletions src/linktools/cli/commands/common/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ def on_init_android(self):
self.logger.warning(f"initialize adb failed: {e}")

try:
from linktools.frida.android import AndroidFridaServer
from linktools.frida import FridaAndroidServer
self.logger.info("initialize android frida server ...")
AndroidFridaServer.setup(abis=["arm", "arm64"])
FridaAndroidServer.setup(abis=["arm", "arm64"])
except Exception as e:
self.logger.warning(f"initialize android frida server failed: {e}")

Expand Down Expand Up @@ -171,8 +171,8 @@ def on_alias(self, shell: str = DEFAULT_SHELL, sync: bool = False):
@subcommand_argument("version", metavar="VERSION", nargs="?",
help="java version, such as 11.0.23 / 17.0.11 / 22.0.1")
def on_java_home(self, version: str = None, shell: str = DEFAULT_SHELL):
from linktools.cli.commands.common import tools
cmdline = list2cmdline([sys.executable, "-m", tools.__name__, "java"])
from linktools.cli import stub
cmdline = list2cmdline([sys.executable, "-m", stub.__name__, "tool", "java"])

java = self.environ.tools["java"]
if version:
Expand All @@ -181,26 +181,22 @@ def on_java_home(self, version: str = None, shell: str = DEFAULT_SHELL):
lines = []
if shell in ("bash", "zsh"):
lines.append(f"alias java='{cmdline}'")
lines.append(f"export JAVA_CMDLINE=''")
lines.append(f"export JAVA_VERSION='{java.get('version')}'")
lines.append(f"export JAVA_HOME='{java.get('home_path')}'")
lines.append(f"export PATH=\"$JAVA_HOME/bin:$PATH\"")
elif shell in ("fish",):
lines.append(f"alias java '{cmdline}'")
lines.append(f"set -x JAVA_CMDLINE ''")
lines.append(f"set -x JAVA_VERSION '{java.get('version')}'")
lines.append(f"set -x JAVA_HOME '{java.get('home_path')}'")
lines.append(f"set -x PATH \"$JAVA_HOME/bin\" \"$PATH\"")
elif shell in ("tcsh",):
lines.append(f"alias java '{cmdline}'")
lines.append(f"setenv JAVA_CMDLINE ''")
lines.append(f"setenv JAVA_VERSION '{java.get('version')}'")
lines.append(f"setenv JAVA_HOME '{java.get('home_path')}'")
lines.append(f"setenv PATH \"$JAVA_HOME/bin:$PATH\"")
elif shell in ("powershell",):
lines.append(f"function __tool_java__ {{ {cmdline} $args }}")
lines.append(f"Set-Alias -Name java -Value __tool_java__")
lines.append(f"$env:JAVA_CMDLINE=' '")
lines.append(f"$env:JAVA_VERSION='{java.get('version')}'")
lines.append(f"$env:JAVA_HOME='{java.get('home_path')}'")
lines.append(f"$env:PATH=\"$env:JAVA_HOME\\bin;$env:PATH\"")
Expand Down
56 changes: 56 additions & 0 deletions src/linktools/cli/stub.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@author : Hu Ji
@file : stub.py
@time : 2024/8/6 16:34
@site : https://github.com/ice-black-tea
@software: PyCharm
,----------------, ,---------,
,-----------------------, ," ,"|
," ,"| ," ," |
+-----------------------+ | ," ," |
| .-----------------. | | +---------+ |
| | | | | | -==----'| |
| | $ sudo rm -rf / | | | | | |
| | | | |/----|`---= | |
| | | | | ,/|==== ooo | ;
| | | | | // |(((( [33]| ,"
| `-----------------' |," .;'| |(((( | ,"
+-----------------------+ ;; | | |,"
/_)______________(_/ //' | +---------+
___________________________/___ `,
/ oooooooooooooooo .o. oooo /, `,"-----------
/ ==ooooooooooooooo==.o. ooo= // ,``--{)B ,"
/_==__==========__==_ooo__ooo=_/' /___________,"
"""
import sys

from ..types import Error

if __name__ == '__main__':

index = 1

if len(sys.argv) <= index:
raise Error("Invalid arguments: missing type")
type = sys.argv[index]
index += 1

if type == "tool":
from linktools import environ

if len(sys.argv) <= index:
raise Error("Invalid arguments: missing name")
name = sys.argv[index]
index += 1

exit(
environ.get_tool(name, cmdline=None)
.popen(*sys.argv[index:])
.call()
)

raise Error(f"Invalid arguments: unknown type `{type}`")
4 changes: 2 additions & 2 deletions src/linktools/utils/_subprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
import shlex
import subprocess
import threading
from typing import AnyStr, Tuple, Optional, IO, Callable, Any, Dict, Union, List
from typing import AnyStr, Tuple, Optional, IO, Callable, Any, Dict, Union, List, Iterable

from .._environ import environ
from ..decorator import cached_property, timeoutable
from ..types import TimeoutType


def list2cmdline(args: List[str]) -> str:
def list2cmdline(args: Iterable[str]) -> str:
return subprocess.list2cmdline(args)


Expand Down
51 changes: 31 additions & 20 deletions src/linktools/utils/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -569,37 +569,34 @@ def get_machine():

if SYSTEM in ("darwin", "linux"):

import pwd


def get_user(uid: int = None):
"""
获取用户名,如果没有指定uid则返回当前用户名
"""
if uid is not None:
import pwd
return pwd.getpwuid(int(uid))
else:
return getpass.getuser()
return pwd.getpwuid(int(uid)) \
if uid is not None \
else getpass.getuser()


def get_uid(user: str = None):
"""
获取用户ID,如果没有指定用户则返回当前用户ID
"""
if user:
import pwd
return pwd.getpwnam(str(user)).pw_uid
else:
return os.getuid()
return pwd.getpwnam(str(user)).pw_uid \
if user is not None \
else os.getuid()


def get_gid(user: str = None):
"""
获取用户组ID,如果没有指定用户则返回当前用户组ID
"""
if user:
import pwd
return pwd.getpwnam(str(user)).pw_gid
else:
return os.getgid()
return pwd.getpwnam(str(user)).pw_gid \
if user is not None \
else os.getgid()


def get_shell_path():
Expand All @@ -611,7 +608,6 @@ def get_shell_path():
if shell_path and os.path.exists(shell_path):
return shell_path
try:
import pwd
return pwd.getpwnam(get_user()).pw_shell
except:
return shutil.which("zsh") or shutil.which("bash") or shutil.which("sh")
Expand All @@ -620,21 +616,21 @@ def get_shell_path():

def get_user(uid: int = None):
"""
获取当前用户,固定为当前用户名
获取当前用户,windows固定为当前用户名
"""
return getpass.getuser()


def get_uid(user: str = None):
"""
获取用户ID,固定为0
获取用户ID,windows固定为0
"""
return 0


def get_gid(user: str = None):
"""
获取用户组ID,固定为0
获取用户组ID,windows固定为0
"""
return 0

Expand All @@ -643,27 +639,42 @@ def get_shell_path():
"""
获取当前用户shell路径
"""
shell_path = shutil.which("powershell") or shutil.which("cmd")
if shell_path:
return shell_path
if "ComSpec" in os.environ:
shell_path = os.environ["ComSpec"]
if shell_path and os.path.exists(shell_path):
return shell_path
return shutil.which("powershell") or shutil.which("cmd")
raise NotImplementedError(f"Unsupported system `{SYSTEM}`")

else:

def get_user(uid: int = None):
"""
获取用户名,如果没有指定uid则返回当前用户名,windows固定为当前用户名
"""
raise NotImplementedError(f"Unsupported system `{SYSTEM}`")


def get_uid(user: str = None):
"""
获取用户ID,如果没有指定用户则返回当前用户ID,windows固定为0
"""
raise NotImplementedError(f"Unsupported system `{SYSTEM}`")


def get_gid(user: str = None):
"""
获取用户组ID,如果没有指定用户则返回当前用户组ID,windows固定为0
"""
raise NotImplementedError(f"Unsupported system `{SYSTEM}`")


def get_shell_path():
"""
获取当前用户shell路径
"""
raise NotImplementedError(f"Unsupported system `{SYSTEM}`")


Expand Down

0 comments on commit 0d23608

Please sign in to comment.