Skip to content

Instantly share code, notes, and snippets.

@joshcangit
Last active January 22, 2023 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshcangit/7c404c0debf3eb98f8678ac50ebb9b4c to your computer and use it in GitHub Desktop.
Save joshcangit/7c404c0debf3eb98f8678ac50ebb9b4c to your computer and use it in GitHub Desktop.
Wrapper script for meson.pyz (pre-release version)
#!/usr/bin/env python3
from asyncio import run as arun
from os import chmod
from pathlib import Path
from shutil import move, rmtree
from stat import S_IWRITE
from subprocess import run, PIPE, STDOUT, CalledProcessError
from sys import argv, executable, stdout
from tempfile import TemporaryDirectory
from zipapp import create_archive
try: from packaging.version import Version
except ModuleNotFoundError:
from pkg_resources import packaging
Version = packaging.version.Version
del packaging
def if_exists(fp):
if(Path(fp).exists()):
return fp
else: return None
def cmd_output(cmd):
result = run(cmd, shell=True, text=True, check=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
return result.stdout
def latest_tag(url):
tags = cmd_output(f"git ls-remote --refs --tags {url}.git").split()
tags[:] = [x.removeprefix('refs/tags/') for x in tags if x.startswith('refs/tags/')]
tags.sort(key=Version)
return tags[-1]
def redo_readonly(func, path, _):
if (if_exists(path)):
chmod(path, S_IWRITE)
func(path)
async def install(url, exe, version):
options = {
"source": "meson",
"outfile": exe,
"interpreter": "/usr/bin/env python3",
"compress": True
}
with TemporaryDirectory() as d:
try: run(f"git -C {d} clone -b {version} {url}.git", shell=True, check=True)
except CalledProcessError as e: print(e)
else:
source = Path(d, options["source"]).resolve()
move(source / 'meson.py', Path(d, '__main__.py'))
move(source / 'mesonbuild', Path(d, 'mesonbuild'))
rmtree(Path(source),onerror=redo_readonly)
create_archive(d, interpreter=options["interpreter"], target=options["outfile"], compressed=options["compress"])
if (if_exists(exe)):
try: move(exe,dirpath / exe)
except IOError:
admin_cmd = f"from pathlib import Path\nfrom shutil import copymode, move, chown\nmove('{exe}','{dirpath / exe}')\nchown('{dirpath / exe}',user='{Path(dirpath).owner()}',group='{Path(dirpath).group()}')\ncopymode('{__file__}','{dirpath / exe}')"
run(f'sudo python -c "{admin_cmd}"', shell=True, check=True)
meson = "meson.pyz"
repo_url = "https://github.com/mesonbuild/meson"
latest_version = latest_tag(repo_url)
dirpath = Path(__file__).parent.absolute()
subcmd = "pyz"
if (if_exists(dirpath / meson)):
if (argv == [argv[0], subcmd]):
current_version = cmd_output([f"{executable} {dirpath / meson} --version"]).strip()
if (Version(current_version) < Version(latest_version)):
arun(install(repo_url, meson, latest_version))
else: print("Meson is up to date")
else:
argv[:] = [f"\"{x}\"" if " " in x else x for x in argv]
run([executable, f"{dirpath / meson}"] + argv[1:])
else:
if (argv == [argv[0], subcmd]): arun(install(repo_url, meson, latest_version))
else: print(f"\nCommand 'meson' not found, but can be installed with:\n\nmeson {subcmd}\n")
@joshcangit
Copy link
Author

joshcangit commented Jul 17, 2022

Wrapper script for meson.pyz (pre-release version)

Registering as command

On Linux / BSD / macOS

PATH environment

  • Place this script inside any folder in your PATH environment.

e.g. /usr/local/bin or ~/.local/bin

  • Instead if you want it in a different folder, create a folder.
    Then, add the contents as below to a profile file, corresponding to on the folder you made, to append to your PATH environment.
    e.g. ~/.meson/bin
if [ -d "$HOME/.meson/bin" ] ; then
    export PATH="$PATH:$HOME/.meson/bin"
fi

The per-user profile file is .profile.
Shell specific files are either .bash-profile for Bash and .zsh_profile for Z shell.
System level profile files are either /etc/profile or a .sh file in /etc/profile.d

Rename file

  • Rename this file to remove the file extension.

i.e. Use meson as filename.

On Windows

Path environment

Place this script inside any folder in your Path environment.

e.g. %SYSTEMROOT%\System32\WindowsPowerShell\v1.0

  • Instead if you want it in a different folder, create a folder.
    Then, open sysdm.cpl a.k.a System Properties.

Windows 10/8.1/7:
Control Panel -> System and Security -> System -> Advanced system settings
Windows 11:
Settings -> System -> About -> Related links section -> Advanced system settings

  • After that, go to the Environment Variables dialog to add the folder path either with the New or Browse... button.

In System Properties -> Advanced tab -> Environment Variables... button
Either Path in the User variables or System variables section.

Add .cmd script.

Create a meson.cmd script, in the same folder, with the contents as below

@echo off
meson.py %*

Do not use this with another Meson instance installed.

This is if you prefer to use Meson directly from the GitHub repository through this script.

Dependencies

Python3

This script requires Python 3.6 and above because I have use formatted string literals.

I prefer to do use this over % or format().

Anyway, Meson itself requires at least Python 3.7.

Also, Python 2 is already deprecated so it should be safe to assume it won't be used.

Git

This script uses git to fetch the repository from GitHub.

Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency.

sudo

On Windows, you can install gsudo if just in case when this script uses sudo for admin rights to a folder.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment