Skip to content

Commit

Permalink
Merge pull request #152 from sambhavnoobcoder/Terminal-Printing-Code-…
Browse files Browse the repository at this point in the history
…Editing

Add terminal code highlighting and editor opening functionality #150
  • Loading branch information
bishoy-at-pieces authored Jul 29, 2024
2 parents ae7eeae + d68581e commit 29c2f36
Show file tree
Hide file tree
Showing 8 changed files with 107 additions and 19 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
# Changelog
## July 26th,2024

- Add the feature to print the code with syntax highlighting in the terminal
- Add the feature allowing to configure favourite editor and open the code directly in editor of choice

## July 24th, 2024

- Add select menu for the list command
Expand Down
2 changes: 1 addition & 1 deletion src/pieces/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
try:
__version__ = importlib.metadata.version("pieces-cli")
except importlib.metadata.PackageNotFoundError:
print("Could not find the 'pieces' package in the Python environment. Is it installed?")
print("Could not find the 'pieces-cli' package in the Python environment. Is it installed?")
__version__ = "unknown"

8 changes: 7 additions & 1 deletion src/pieces/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,16 @@ def __init__(self):

def add_subparsers(self):

# Subparser for the 'config' command
config_parser = self.command_parser.add_parser('config', help='Configure settings')
config_parser.add_argument('--editor',"-e",dest="editor", type=str, help='Set the default code editor')
config_parser.set_defaults(func=ConfigCommands.config)

# Subparser for the 'lists' command
list_parser = self.command_parser.add_parser('list', help='List the assets or apps or models')
list_parser.add_argument('type', nargs='?', type=str ,default="assets", help='type of the list',choices=["assets","apps","models"])
list_parser.add_argument('max_assets', nargs='?', type=int ,default=10, help='Max number of assets')
list_parser.add_argument("--editor","-e",dest="editor",action="store_true" ,default=False, help="Open the choosen asset in the editor")
list_parser.set_defaults(func=ListCommand.list_command)


Expand Down Expand Up @@ -133,4 +139,4 @@ def main():
cli.run()

if __name__ == "__main__":
main()
main()
53 changes: 41 additions & 12 deletions src/pieces/assets/assets_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
from .assets_api import AssetsCommandsApi
from pieces.gui import show_error,print_model_details,space_below,double_line,deprecated
from pieces.settings import Settings

from pieces.commands.config_command import ConfigCommands
import subprocess
from pygments import highlight
from pygments.lexers import get_lexer_by_name, guess_lexer
from pygments.formatters import TerminalFormatter

def check_assets_existence(func):
"""Decorator to ensure user has assets."""
Expand Down Expand Up @@ -40,23 +44,48 @@ class AssetsCommands:
@classmethod
@check_assets_existence
@deprecated("open","list assets")
def open_asset(cls,**kwargs):
item_index = kwargs.get('ITEM_INDEX',1)
if not item_index:
item_index = 1
def open_asset(cls, **kwargs):
item_index = kwargs.get("ITEM_INDEX",1)
asset_ids = AssetsCommandsApi().assets_snapshot
try:
cls.current_asset = list(asset_ids.keys())[item_index-1] # because we begin from 1
cls.current_asset = list(asset_ids.keys())[item_index-1] # because we begin from 1
except IndexError:
show_error("Invalid asset index or asset not found.","Please choose from the list or use 'pieces list assets'")
return

return show_error("Invalid asset index or asset not found.", "Please choose from the list or use 'pieces list assets'")

asset_dict = AssetsCommandsApi.extract_asset_info(AssetsCommandsApi.get_asset_snapshot(cls.current_asset))


print_model_details(asset_dict["name"], asset_dict["created_at"], asset_dict["updated_at"], asset_dict["type"], asset_dict["language"])

filepath = export_code_to_file(asset_dict["raw"], asset_dict["name"], asset_dict["language"])
code_content = asset_dict["raw"]
open_in_editor = kwargs.get('editor')

# Check if -e flag is used or open_in_editor is True
if open_in_editor:
config = ConfigCommands.load_config()
editor = config.get('editor')
if editor:
# Save the code to a file in the default directory
file_path = export_code_to_file(code_content, asset_dict["name"], asset_dict["language"])

# Open the file with the configured editor
try:
subprocess.run([editor, file_path], shell=True)
except Exception as e:
show_error("Error in opening",e)

print_model_details(asset_dict["name"],asset_dict["created_at"],asset_dict["updated_at"],asset_dict["type"],asset_dict["language"],filepath)
else:
print("No editor configured. Use 'pieces config editor <editor_command>' to set an editor.")
else:
# Determine the lexer
try:
lexer = get_lexer_by_name(asset_dict["language"], stripall=True)
except:
lexer = guess_lexer(code_content)

# Print the code with syntax highlighting
formatted_code = highlight(code_content, lexer, TerminalFormatter())
print("\nCode content:")
print(formatted_code)


@classmethod
Expand Down
4 changes: 3 additions & 1 deletion src/pieces/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
from .list_command import ListCommand
from .version_command import version
from .signout_command import sign_out
from .config_command import ConfigCommands

__all__ = ['loop',
'version',
'search',
'change_model',
'sign_out',
'ListCommand']
'ListCommand',
'ConfigCommands']

43 changes: 43 additions & 0 deletions src/pieces/commands/config_command.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import os
from pieces.settings import Settings
import json

#Ensure the data_path directory exists
os.makedirs(Settings.pieces_data_dir, exist_ok=True)
CONFIG_FILE = os.path.join(Settings.pieces_data_dir, "pieces_config.json")

class ConfigCommands:

@classmethod
def load_config(cls):
if os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, 'r') as f:
content = f.read().strip()
if content:
return json.loads(content)
else:
# print("Config file is empty. Creating a new configuration.")
return {}
except json.JSONDecodeError:
print("Invalid JSON in config file. Creating a new configuration.")
return {}
else:
# print("Config file does not exist. Creating a new configuration.")
return {}

@classmethod
def save_config(cls, config):
with open(CONFIG_FILE, 'w') as f:
json.dump(config, f)

@classmethod
def config(cls, **kwargs):
config = cls.load_config()
if 'editor' in kwargs:
config['editor'] = kwargs['editor']
cls.save_config(config)
print(f"Editor set to: {kwargs['editor']}")
else:
print("Current configuration:")
print(f"Editor: {config.get('editor', 'Not set')}")
6 changes: 3 additions & 3 deletions src/pieces/commands/list_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,20 +78,20 @@ def list_command(cls, **kwargs):
max_assets = 10

if type == "assets":
cls.list_assets(max_assets)
cls.list_assets(**kwargs)
elif type == "apps":
cls.list_apps()
elif type == "models":
cls.list_models()

@classmethod
@check_assets_existence
def list_assets(cls, max_assets: int = 10):
def list_assets(cls, max_assets: int = 10,**kwargs):
assets_snapshot = AssetsCommandsApi().assets_snapshot
assets = []
for i, uuid in enumerate(list(assets_snapshot.keys())[:max_assets], start=1):
asset = AssetsCommandsApi.get_asset_snapshot(uuid)
assets.append((f"{i}: {asset.name}", {"ITEM_INDEX":i,"show_warning":False}))
assets.append((f"{i}: {asset.name}", {"ITEM_INDEX":i,"show_warning":False,**kwargs})) # Pass the args to the open command

select_menu = PiecesSelectMenu(assets, AssetsCommands.open_asset)
select_menu.run()
Expand Down
5 changes: 4 additions & 1 deletion src/pieces/gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,9 @@ def print_help():
print(" create - Creates a new asset based on what you've copied to your clipboard")
print(" clear - to clear the terminal")
print()
print(" config - View current configuration")
print(" config editor=x - Set the editor to 'x' in the configuration")
print()
print(" change_model x - Change the model that is used in the ask command defaults to chatGPT 3.5 similar to list models")
print(" ask \"ask\" - Asks a single question to the model selected in change model. Default timeout set to 10 seconds")
print(" --snippets,-s - Add a certain snippet or snippets using the index check list assets command to the ask command")
Expand Down Expand Up @@ -173,4 +176,4 @@ def wrapper(*args, **kwargs):
print(f"\033[93m WARNING: `{command}` is deprecated and will be removed in later versions\nPlease use `{instead}` instead \033[0m")
func(*args,**kwargs)
return wrapper
return decorator
return decorator

0 comments on commit 29c2f36

Please sign in to comment.