mirror of
https://github.com/daylinmorgan/task.mk.git
synced 2024-12-22 01:50:44 -06:00
feat: show deps for phony targets with no recipe
This commit is contained in:
parent
bc4c95aab9
commit
63eb8ac754
2 changed files with 130 additions and 76 deletions
10
src/help.py
10
src/help.py
|
@ -98,7 +98,6 @@ def parse_goal(file, goal):
|
||||||
goals = goal_pattern.findall(file)
|
goals = goal_pattern.findall(file)
|
||||||
matched_goal = [i for i in goals if goal in i.split()]
|
matched_goal = [i for i in goals if goal in i.split()]
|
||||||
output = []
|
output = []
|
||||||
|
|
||||||
if matched_goal:
|
if matched_goal:
|
||||||
output.append(recipe_help_header(matched_goal[0]))
|
output.append(recipe_help_header(matched_goal[0]))
|
||||||
deps = get_goal_deps(matched_goal[0])
|
deps = get_goal_deps(matched_goal[0])
|
||||||
|
@ -115,8 +114,13 @@ def parse_goal(file, goal):
|
||||||
output.append(divider(max((len(l.strip()) for l in recipe))))
|
output.append(divider(max((len(l.strip()) for l in recipe))))
|
||||||
output.append("\n".join(recipe))
|
output.append("\n".join(recipe))
|
||||||
else:
|
else:
|
||||||
output.append(f"{ansi.b_red}ERROR{ansi.end} Failed to find goal: {goal}")
|
deps = get_goal_deps(goal)
|
||||||
|
if deps:
|
||||||
|
output.append(recipe_help_header(goal))
|
||||||
|
output.extend(deps)
|
||||||
|
|
||||||
|
if not output:
|
||||||
|
output.append(f"{ansi.style('ERROR','b_red')}: Failed to find goal: {goal}")
|
||||||
return output
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
@ -184,7 +188,7 @@ def main():
|
||||||
help_args = os.getenv("HELP_ARGS")
|
help_args = os.getenv("HELP_ARGS")
|
||||||
if help_args:
|
if help_args:
|
||||||
print_arg_help(help_args)
|
print_arg_help(help_args)
|
||||||
print(a.faint)
|
print(ansi.faint)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
else:
|
else:
|
||||||
print_help()
|
print_help()
|
||||||
|
|
196
task.mk
196
task.mk
|
@ -1,7 +1,7 @@
|
||||||
# }> [github.com/daylinmorgan/task.mk] <{ #
|
# }> [github.com/daylinmorgan/task.mk] <{ #
|
||||||
# Copyright (c) 2022 Daylin Morgan
|
# Copyright (c) 2022 Daylin Morgan
|
||||||
# MIT License
|
# MIT License
|
||||||
# version: v22.9.19-5-g5f593e3-dev
|
# version: v22.9.19-12-gbc4c95a-dev
|
||||||
#
|
#
|
||||||
# task.mk should be included at the bottom of your Makefile with `-include .task.mk`
|
# task.mk should be included at the bottom of your Makefile with `-include .task.mk`
|
||||||
# See below for the standard configuration options that should be set prior to including this file.
|
# See below for the standard configuration options that should be set prior to including this file.
|
||||||
|
@ -12,12 +12,12 @@ ACCENT_STYLE ?= b_yellow
|
||||||
PARAMS_STYLE ?= $(ACCENT_STYLE)
|
PARAMS_STYLE ?= $(ACCENT_STYLE)
|
||||||
GOAL_STYLE ?= $(ACCENT_STYLE)
|
GOAL_STYLE ?= $(ACCENT_STYLE)
|
||||||
MSG_STYLE ?= faint
|
MSG_STYLE ?= faint
|
||||||
DIVIDER_STYLE ?= default
|
|
||||||
DIVIDER ?= ─
|
DIVIDER ?= ─
|
||||||
|
DIVIDER_STYLE ?= default
|
||||||
HELP_SEP ?= │
|
HELP_SEP ?= │
|
||||||
# python f-string literals
|
# python f-string literals
|
||||||
EPILOG ?=
|
EPILOG ?=
|
||||||
USAGE ?={ansi.$(HEADER_STYLE)}usage{ansi.end}:\n make <recipe>\n
|
USAGE ?={ansi.header}usage{ansi.end}:\n make <recipe>\n
|
||||||
INHERIT_SHELL ?=
|
INHERIT_SHELL ?=
|
||||||
# ---- [builtin recipes] ---- #
|
# ---- [builtin recipes] ---- #
|
||||||
ifeq (help,$(firstword $(MAKECMDGOALS)))
|
ifeq (help,$(firstword $(MAKECMDGOALS)))
|
||||||
|
@ -25,9 +25,8 @@ ifeq (help,$(firstword $(MAKECMDGOALS)))
|
||||||
export HELP_ARGS
|
export HELP_ARGS
|
||||||
endif
|
endif
|
||||||
## h, help | show this help
|
## h, help | show this help
|
||||||
.PHONY: help h
|
h help:
|
||||||
help h:
|
$(call py,help_py) || { echo "exiting early!"; exit 1; }
|
||||||
$(call py,help_py)
|
|
||||||
.PHONY: _help
|
.PHONY: _help
|
||||||
_help: export SHOW_HIDDEN=true
|
_help: export SHOW_HIDDEN=true
|
||||||
_help: help
|
_help: help
|
||||||
|
@ -51,9 +50,9 @@ tconfirm = $(call py,confirm_py,$(1))
|
||||||
_update-task.mk:
|
_update-task.mk:
|
||||||
$(call tprint,{a.b_cyan}Updating task.mk{a.end})
|
$(call tprint,{a.b_cyan}Updating task.mk{a.end})
|
||||||
curl https://raw.githubusercontent.com/daylinmorgan/task.mk/main/task.mk -o .task.mk
|
curl https://raw.githubusercontent.com/daylinmorgan/task.mk/main/task.mk -o .task.mk
|
||||||
export MAKEFILE_LIST
|
export MAKEFILE_LIST MAKE
|
||||||
ifndef INHERIT_SHELL
|
ifndef INHERIT_SHELL
|
||||||
SHELL := /bin/bash
|
SHELL := $(shell which bash)
|
||||||
endif
|
endif
|
||||||
# ---- [python/bash script runner] ---- #
|
# ---- [python/bash script runner] ---- #
|
||||||
define _newline
|
define _newline
|
||||||
|
@ -84,8 +83,10 @@ import argparse
|
||||||
from collections import namedtuple
|
from collections import namedtuple
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
$(ansi_py)
|
import subprocess
|
||||||
$(quit_make_py)
|
import sys
|
||||||
|
from textwrap import wrap
|
||||||
|
$(utils_py)
|
||||||
MaxLens = namedtuple("MaxLens", "goal msg")
|
MaxLens = namedtuple("MaxLens", "goal msg")
|
||||||
pattern = re.compile(
|
pattern = re.compile(
|
||||||
r"^## (?P<goal>.*?) \| (?P<msg>.*?)(?:\s?\| args: (?P<msgargs>.*?))?$$|^### (?P<rawmsg>.*?)?(?:\s?\| args: (?P<rawargs>.*?))?$$"
|
r"^## (?P<goal>.*?) \| (?P<msg>.*?)(?:\s?\| args: (?P<msgargs>.*?))?$$|^### (?P<rawmsg>.*?)?(?:\s?\| args: (?P<rawargs>.*?))?$$"
|
||||||
|
@ -100,9 +101,11 @@ def parseargs(argstring):
|
||||||
parser.add_argument("-gs", "--goal-style", type=str)
|
parser.add_argument("-gs", "--goal-style", type=str)
|
||||||
parser.add_argument("--hidden", action="store_true")
|
parser.add_argument("--hidden", action="store_true")
|
||||||
return parser.parse_args(argstring.split())
|
return parser.parse_args(argstring.split())
|
||||||
|
def divider(len):
|
||||||
|
return ansi.style(f" {cfg.div*len}", "div_style")
|
||||||
def gen_makefile():
|
def gen_makefile():
|
||||||
makefile = ""
|
makefile = ""
|
||||||
for file in os.getenv("MAKEFILE_LIST").split():
|
for file in os.getenv("MAKEFILE_LIST", "").split():
|
||||||
with open(file, "r") as f:
|
with open(file, "r") as f:
|
||||||
makefile += f.read() + "\n\n"
|
makefile += f.read() + "\n\n"
|
||||||
return makefile
|
return makefile
|
||||||
|
@ -132,58 +135,76 @@ def recipe_help_header(goal):
|
||||||
item[0].get("msgargs", ""),
|
item[0].get("msgargs", ""),
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
return f" {ansi.style(goal,'$(GOAL_STYLE)')}:"
|
return f" {ansi.style(goal,'goal')}"
|
||||||
|
def get_goal_deps(goal="task.mk"):
|
||||||
|
make = os.getenv("MAKE", "make")
|
||||||
|
database = subprocess.check_output([make, "-p", "-n"], universal_newlines=True)
|
||||||
|
dep_pattern = re.compile(r"^" + goal + ":(.*)?")
|
||||||
|
for line in database.splitlines():
|
||||||
|
match = dep_pattern.search(line)
|
||||||
|
if match and match.groups()[0]:
|
||||||
|
return wrap(
|
||||||
|
f"{ansi.style('deps','default')}: {ansi.style(match.groups()[0].strip(),'msg')}",
|
||||||
|
initial_indent=" ",
|
||||||
|
subsequent_indent=" ",
|
||||||
|
)
|
||||||
def parse_goal(file, goal):
|
def parse_goal(file, goal):
|
||||||
goals = goal_pattern.findall(file)
|
goals = goal_pattern.findall(file)
|
||||||
matched_goal = [i for i in goals if goal in i.split()]
|
matched_goal = [i for i in goals if goal in i.split()]
|
||||||
output = []
|
output = []
|
||||||
if matched_goal:
|
if matched_goal:
|
||||||
output.append(recipe_help_header(matched_goal[0]))
|
output.append(recipe_help_header(matched_goal[0]))
|
||||||
|
deps = get_goal_deps(matched_goal[0])
|
||||||
|
if deps:
|
||||||
|
output.extend(deps)
|
||||||
lines = file.splitlines()
|
lines = file.splitlines()
|
||||||
loc = [n for n, l in enumerate(lines) if l.startswith(f"{matched_goal[0]}:")][0]
|
loc = [n for n, l in enumerate(lines) if l.startswith(f"{matched_goal[0]}:")][0]
|
||||||
recipe = []
|
recipe = []
|
||||||
for line in lines[loc + 1 :]:
|
for line in lines[loc + 1 :]:
|
||||||
if not line.startswith("\t"):
|
if not line.startswith("\t"):
|
||||||
break
|
break
|
||||||
recipe.append(line)
|
recipe.append(f" {line.strip()}")
|
||||||
output.append(divider(max((len(l) for l in recipe)) + 5))
|
output.append(divider(max((len(l.strip()) for l in recipe))))
|
||||||
output.append("\n".join(recipe) + "\n")
|
output.append("\n".join(recipe))
|
||||||
else:
|
else:
|
||||||
output.append(f"{ansi.b_red}ERROR{ansi.end} Failed to find goal: {goal}")
|
deps = get_goal_deps(goal)
|
||||||
|
if deps:
|
||||||
|
output.append(recipe_help_header(goal))
|
||||||
|
output.extend(deps)
|
||||||
|
if not output:
|
||||||
|
output.append(f"{ansi.style('ERROR','b_red')}: Failed to find goal: {goal}")
|
||||||
return output
|
return output
|
||||||
def fmt_goal(goal, msg, max_goal_len, argstr):
|
def fmt_goal(goal, msg, max_goal_len, argstr):
|
||||||
args = parseargs(argstr)
|
args = parseargs(argstr)
|
||||||
goal_style = args.goal_style.strip() if args.goal_style else "$(GOAL_STYLE)"
|
goal_style = args.goal_style.strip() if args.goal_style else "goal"
|
||||||
msg_style = args.msg_style.strip() if args.msg_style else "$(MSG_STYLE)"
|
msg_style = args.msg_style.strip() if args.msg_style else "msg"
|
||||||
return (
|
return (
|
||||||
ansi.style(f" {goal:>{max_goal_len}}", goal_style)
|
ansi.style(f" {goal:>{max_goal_len}}", goal_style)
|
||||||
+ f" $(HELP_SEP) "
|
+ f" $(HELP_SEP) "
|
||||||
+ ansi.style(msg, msg_style)
|
+ ansi.style(msg, msg_style)
|
||||||
)
|
)
|
||||||
def divider(len):
|
|
||||||
return ansi.style(f" {'$(DIVIDER)'*len}", "$(DIVIDER_STYLE)")
|
|
||||||
def fmt_rawmsg(msg, argstr, maxlens):
|
def fmt_rawmsg(msg, argstr, maxlens):
|
||||||
args = parseargs(argstr)
|
args = parseargs(argstr)
|
||||||
lines = []
|
lines = []
|
||||||
msg_style = args.msg_style.strip() if args.msg_style else "$(MSG_STYLE)"
|
msg_style = args.msg_style.strip() if args.msg_style else "msg"
|
||||||
if not os.getenv("SHOW_HIDDEN") and args.hidden:
|
if not os.getenv("SHOW_HIDDEN") and args.hidden:
|
||||||
return []
|
return []
|
||||||
if msg:
|
if msg:
|
||||||
if args.align == "sep":
|
if args.align == "sep":
|
||||||
lines.append(
|
lines.append(
|
||||||
f"{' '*(maxlens.goal+len('$(HELP_SEP)')+4)}{ansi.style(msg,msg_style)}"
|
f"{' '*(maxlens.goal+len(cfg.sep)+4)}{ansi.style(msg,msg_style)}"
|
||||||
)
|
)
|
||||||
elif args.align == "center":
|
elif args.align == "center":
|
||||||
lines.append(f" {ansi.style(msg.center(sum(maxlens)),msg_style)}")
|
lines.append(f" {ansi.style(msg.center(sum(maxlens)),msg_style)}")
|
||||||
else:
|
else:
|
||||||
lines.append(f" {ansi.style(msg,msg_style)}")
|
lines.append(f" {ansi.style(msg,msg_style)}")
|
||||||
if args.divider:
|
if args.divider:
|
||||||
lines.append(divider(len("$(HELP_SEP)") + sum(maxlens) + 2))
|
lines.append(divider(len(cfg.sep) + sum(maxlens) + 2))
|
||||||
if args.whitespace:
|
if args.whitespace:
|
||||||
lines.append("\n")
|
lines.append("\n")
|
||||||
return lines
|
return lines
|
||||||
def print_help():
|
def print_help():
|
||||||
lines = [f"""$(USAGE)"""]
|
lines = [cfg.usage]
|
||||||
items = list(parse_help(gen_makefile()))
|
items = list(parse_help(gen_makefile()))
|
||||||
maxlens = MaxLens(
|
maxlens = MaxLens(
|
||||||
*(max((len(item[x]) for item in items if x in item)) for x in ["goal", "msg"])
|
*(max((len(item[x]) for item in items if x in item)) for x in ["goal", "msg"])
|
||||||
|
@ -197,25 +218,78 @@ def print_help():
|
||||||
)
|
)
|
||||||
if "rawmsg" in item:
|
if "rawmsg" in item:
|
||||||
lines.extend(fmt_rawmsg(item["rawmsg"], item.get("rawargs", ""), maxlens))
|
lines.extend(fmt_rawmsg(item["rawmsg"], item.get("rawargs", ""), maxlens))
|
||||||
lines.append(f"""$(EPILOG)""")
|
lines.append(cfg.epilog)
|
||||||
print("\n".join(lines))
|
print("\n".join(lines))
|
||||||
def print_arg_help(help_args):
|
def print_arg_help(help_args):
|
||||||
|
print(f"{ansi.style('task.mk recipe help','header')}\n")
|
||||||
for arg in help_args.split():
|
for arg in help_args.split():
|
||||||
print(f"{ansi.style('task.mk recipe help','$(HEADER_STYLE)')}\n")
|
|
||||||
print("\n".join(parse_goal(gen_makefile(), arg)))
|
print("\n".join(parse_goal(gen_makefile(), arg)))
|
||||||
def main():
|
def main():
|
||||||
help_args = os.getenv("HELP_ARGS")
|
help_args = os.getenv("HELP_ARGS")
|
||||||
if help_args:
|
if help_args:
|
||||||
quit_make()
|
|
||||||
print_arg_help(help_args)
|
print_arg_help(help_args)
|
||||||
|
print(ansi.faint)
|
||||||
|
sys.exit(1)
|
||||||
else:
|
else:
|
||||||
print_help()
|
print_help()
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
endef
|
endef
|
||||||
define ansi_py
|
define info_py
|
||||||
|
$(utils_py)
|
||||||
|
print(f"""$(2)""")
|
||||||
|
endef
|
||||||
|
define print_ansi_py
|
||||||
|
$(utils_py)
|
||||||
|
sep = f"$(HELP_SEP)"
|
||||||
|
codes_names = {getattr(ansi, attr): attr for attr in ansi.__dict__}
|
||||||
|
for code in sorted(codes_names.keys(), key=lambda item: (len(item), item)):
|
||||||
|
print(f"{codes_names[code]:>20} {sep} {code+'*****'+ansi.end} {sep} {repr(code)}")
|
||||||
|
endef
|
||||||
|
define vars_py
|
||||||
|
import os
|
||||||
|
$(utils_py)
|
||||||
|
vars = "$2".split()
|
||||||
|
length = max((len(v) for v in vars))
|
||||||
|
print(f"{ansi.header}vars{ansi.end}:\n")
|
||||||
|
for v in vars:
|
||||||
|
print(f" {ansi.params}{v:<{length}}{ansi.end} = {os.getenv(v)}")
|
||||||
|
print()
|
||||||
|
endef
|
||||||
|
define confirm_py
|
||||||
|
import sys
|
||||||
|
$(utils_py)
|
||||||
|
def confirm():
|
||||||
|
"""
|
||||||
|
Ask user to enter Y or N (case-insensitive).
|
||||||
|
:return: True if the answer is Y.
|
||||||
|
:rtype: bool
|
||||||
|
"""
|
||||||
|
answer = ""
|
||||||
|
while answer not in ["y", "n"]:
|
||||||
|
answer = input(f"""$(2) {a.b_red}[Y/n]{a.end} """).lower()
|
||||||
|
return answer == "y"
|
||||||
|
if confirm():
|
||||||
|
sys.exit()
|
||||||
|
else:
|
||||||
|
sys.exit(1)
|
||||||
|
endef
|
||||||
|
define utils_py
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
from dataclasses import dataclass
|
||||||
|
@dataclass
|
||||||
|
class Config:
|
||||||
|
header: str
|
||||||
|
accent: str
|
||||||
|
params: str
|
||||||
|
goal: str
|
||||||
|
msg: str
|
||||||
|
div: str
|
||||||
|
div_style: str
|
||||||
|
sep: str
|
||||||
|
epilog: str
|
||||||
|
usage: str
|
||||||
color2byte = dict(
|
color2byte = dict(
|
||||||
black=0,
|
black=0,
|
||||||
red=1,
|
red=1,
|
||||||
|
@ -277,6 +351,14 @@ class Ansi:
|
||||||
print("Expected one or three values for bg as a list")
|
print("Expected one or three values for bg as a list")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
return code + end
|
return code + end
|
||||||
|
def add_cfg(self, cfg):
|
||||||
|
cfg_attrs = {
|
||||||
|
attr: getattr(cfg, attr)
|
||||||
|
for attr in cfg.__dict__
|
||||||
|
if attr not in ["div", "sep", "epilog", "usage"]
|
||||||
|
}
|
||||||
|
for name, cfg_attr in cfg_attrs.items():
|
||||||
|
self.setcode(name, getattr(ansi, cfg_attr))
|
||||||
def style(self, text, style):
|
def style(self, text, style):
|
||||||
if style not in self.__dict__:
|
if style not in self.__dict__:
|
||||||
print(f"unknown style: {style}")
|
print(f"unknown style: {style}")
|
||||||
|
@ -284,49 +366,17 @@ class Ansi:
|
||||||
else:
|
else:
|
||||||
return f"{self.__dict__[style]}{text}{self.__dict__['end']}"
|
return f"{self.__dict__[style]}{text}{self.__dict__['end']}"
|
||||||
a = ansi = Ansi()
|
a = ansi = Ansi()
|
||||||
endef
|
cfg = Config(
|
||||||
define info_py
|
"$(HEADER_STYLE)",
|
||||||
$(ansi_py)
|
"$(ACCENT_STYLE)",
|
||||||
print(f"""$(2)""")
|
"$(PARAMS_STYLE)",
|
||||||
endef
|
"$(GOAL_STYLE)",
|
||||||
define print_ansi_py
|
"$(MSG_STYLE)",
|
||||||
$(ansi_py)
|
"$(DIVIDER)",
|
||||||
sep = f"$(HELP_SEP)"
|
"$(DIVIDER_STYLE)",
|
||||||
codes_names = {getattr(ansi, attr): attr for attr in ansi.__dict__}
|
"$(HELP_SEP)",
|
||||||
for code in sorted(codes_names.keys(), key=lambda item: (len(item), item)):
|
f"""$(EPILOG)""",
|
||||||
print(f"{codes_names[code]:>20} {sep} {code+'*****'+ansi.end} {sep} {repr(code)}")
|
f"""$(USAGE)""",
|
||||||
endef
|
)
|
||||||
define vars_py
|
ansi.add_cfg(cfg)
|
||||||
import os
|
|
||||||
$(ansi_py)
|
|
||||||
vars = "$2".split()
|
|
||||||
length = max((len(v) for v in vars))
|
|
||||||
print(f"{ansi.$(HEADER_STYLE)}vars:{ansi.end}\n")
|
|
||||||
for v in vars:
|
|
||||||
print(f" {ansi.b_magenta}{v:<{length}}{ansi.end} = {os.getenv(v)}")
|
|
||||||
print()
|
|
||||||
endef
|
|
||||||
define confirm_py
|
|
||||||
import sys
|
|
||||||
$(ansi_py)
|
|
||||||
$(quit_make_py)
|
|
||||||
def confirm():
|
|
||||||
"""
|
|
||||||
Ask user to enter Y or N (case-insensitive).
|
|
||||||
:return: True if the answer is Y.
|
|
||||||
:rtype: bool
|
|
||||||
"""
|
|
||||||
answer = ""
|
|
||||||
while answer not in ["y", "n"]:
|
|
||||||
answer = input(f"""$(2) {a.b_red}[Y/n]{a.end} """).lower()
|
|
||||||
return answer == "y"
|
|
||||||
if confirm():
|
|
||||||
sys.exit()
|
|
||||||
else:
|
|
||||||
quit_make()
|
|
||||||
endef
|
|
||||||
define quit_make_py
|
|
||||||
import os, signal
|
|
||||||
def quit_make():
|
|
||||||
os.kill(os.getppid(), signal.SIGQUIT)
|
|
||||||
endef
|
endef
|
||||||
|
|
Loading…
Reference in a new issue