Skip to content

Commit

Permalink
Implement FZF adjust option
Browse files Browse the repository at this point in the history
  • Loading branch information
ezh committed Feb 23, 2020
1 parent 7aad9fa commit 1e6a636
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 15 deletions.
31 changes: 23 additions & 8 deletions cloudselect/discovery/kubernetes.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,15 @@ def __init__(self):
def run(self):
"""Collect Kubernetes pods."""
self.log.debug("Discover Kubernetes pods")
return list(self.instances())
instances = list(self.instances())
representation = instances[-1]
del instances[-1]
return (representation, instances)

def instances(self):
"""Collect Kubernetes pods."""
# Array with maximum field length for each element in representation
fields_length = []
for i in self.find():
metadata = self.simplify_metadata(i["metadata"])
container = i["container"]
Expand All @@ -43,6 +48,13 @@ def instances(self):
representation = [instance_id, name, container]
self.enrich_representation(representation, metadata)

# Update maximum field length
for idx, value in enumerate(representation):
if idx >= len(fields_length):
fields_length.append(len(value))
else:
fields_length[idx] = max(fields_length[idx], len(value))

yield PodContainer(
instance_id,
name,
Expand All @@ -58,6 +70,7 @@ def instances(self):
namespace,
metadata["status"]["host_ip"],
)
yield fields_length

@staticmethod
def aws_apply(aws_profile, aws_region):
Expand Down Expand Up @@ -97,24 +110,24 @@ def find(self):
aws_envs = self.aws_apply(aws_profile, aws_region)
pods = self.get_pods(cluster_id, configuration, context)
self.aws_restore(*aws_envs)
for pod in pods.items:
namespace = pod.metadata.namespace
for pod in pods:
namespace = pod["metadata"]["namespace"]
matched = True
if patterns:
matched = False
for i in patterns:
if i.match(namespace) is not None:
matched = True
break
if pod.status.phase == "Running" and matched:
for container in pod.spec.containers:
if pod["status"]["phase"] in ["Running"] and matched:
for container in pod["spec"]["containers"]:
yield {
"aws_profile": aws_profile,
"aws_region": aws_region,
"configuration": configuration,
"container": container.name,
"container": container["name"],
"context": context,
"metadata": pod.to_dict(),
"metadata": pod,
}

def get_pods(self, cluster_id, configuration, context):
Expand All @@ -130,4 +143,6 @@ def get_pods(self, cluster_id, configuration, context):
version.git_version,
)
core_v1 = client.CoreV1Api(api_client=api_client)
return core_v1.list_pod_for_all_namespaces(watch=False)
return [
i.to_dict() for i in core_v1.list_pod_for_all_namespaces(watch=False).items
]
36 changes: 29 additions & 7 deletions cloudselect/selector.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ def complete(self, cline, cpoint):
profiles.append(name)
print("\n".join(sorted(set(profiles))))

@staticmethod
def config():
"""Return selector configuration."""
return Container.config().get("option", {})

def edit(self, configuration):
"""Edit profile or shared configuration file if file is None."""
self.logger.debug("Edit '%s'", configuration)
Expand All @@ -69,17 +74,34 @@ def execute(program, args, **kwargs):
.strip()
)

def fzf_select(self, instances):
def fzf_select(self, representation_maximum_field_length, instances):
"""Invoke FZF with list of instances and return selected."""
fzf_options = Container.config.fzf() or ["-1", "-m", "--with-nth", "2.."]
fzf_options = self.config().get("fzf") or [
"-1",
"-m",
"-e",
"--with-nth",
"2..",
]

def find(instance_id):
return next(x for x in instances if x.instance_id == instance_id)

if Container.config.sort_by():
sort_by = Container.config.sort_by()
def adjust(representation, representation_maximum_field_length):
if self.config().get("adjust"):
for idx, value in enumerate(representation):
representation[idx] = value.ljust(
representation_maximum_field_length[idx],
)
return representation

if self.config().get("sort_by"):
sort_by = self.config().get("sort_by")
instances = sorted(instances, key=lambda x: x.representation[sort_by])
fzf_input = "\n".join("\t".join(i.representation) for i in instances).encode()
fzf_input = "\n".join(
"\t".join(adjust(i.representation, representation_maximum_field_length))
for i in instances
).encode()
selected = self.execute("fzf", fzf_options, input=fzf_input)
if not selected:
sys.exit("Error: No instances selected")
Expand Down Expand Up @@ -135,10 +157,10 @@ def profile_process(self):
report = Container.report()

self.logger.debug("Process profile '%s'", profile_name)
instances = discovery.run()
representation_maximum_field_length, instances = discovery.run()
if not instances:
sys.exit("Error: No instances found")
selected = self.fzf_select(instances)
selected = self.fzf_select(representation_maximum_field_length, instances)
selected = [pathfinder.run(i, instances) for i in selected]
return report.run(selected)

Expand Down

0 comments on commit 1e6a636

Please sign in to comment.