Skip to content

Commit

Permalink
This got far in a few hours, I want to keep making it better!
Browse files Browse the repository at this point in the history
  • Loading branch information
JREAM committed Mar 12, 2017
0 parents commit 4fac893
Show file tree
Hide file tree
Showing 8 changed files with 369 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.pyc
.vscode/
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2017 Jesse Boyer

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
99 changes: 99 additions & 0 deletions cli-aid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
#!/usr/bin/env python
"""This module is a CLI Application to build help and snippets
for you to remember while in terminal.
"""
from __future__ import print_function
import os
import sys

# Current Version
VERSION=0.01

# Path to topic files
PATH_TOPICS = 'topics'

# Get the CLI Args
if len(sys.argv) == 1:
print("""
Please pass two (2) arguments:
- arg1: name of a topic file (try: demo).
- arg2: name of a method within the topic file (try: basic)
Usage $ ./ci_help.py <command> <argument>
Example $ ./cli.py demo basic
""")
sys.exit()
elif len(sys.argv) == 2:
"""
@TODO: Allow one arg only, and list out the method names
for the topic.
"""
elif len(sys.argv) <= 2:
# We want three arguments contain [scriptname, arg1, arg2]
print('Please provide two arguments: <service> <command>')
sys.exit()

# Assign Service and Command, lowercase is safecase!
ARG_SERVICE = sys.argv[1].lower()
ARG_COMMAND = sys.argv[2].lower()

# The module we hope to import
IMPORT_MODULE = '%s.%s' % (PATH_TOPICS, ARG_SERVICE)

# List Topics In Order: [__init__, git, etc]
AVAILABLE_TOPICS = sorted([
# Strip the *.py Extensions for our list
os.path.splitext(x)[0] for x in os.listdir(PATH_TOPICS)
])

# Make sure the TOPIC exists
if ARG_SERVICE not in AVAILABLE_TOPICS:
print("Sorry, the topic %s is not available." % ARG_SERVICE)
sys.exit()

if ARG_SERVICE in AVAILABLE_TOPICS:
REAL_SERVICE = __import__(IMPORT_MODULE, fromlist=[''])

# Make sure we have the ARG_COMMAND
if not hasattr(REAL_SERVICE, ARG_COMMAND):
print('Sorry, the topic %s has no command: %s' % ARG_COMMAND)
sys.exit()

# Process the Command
RUN_METHOD = getattr(REAL_SERVICE, ARG_COMMAND)
RESULT = RUN_METHOD()

# Get Result Type
result_type = None
if isinstance(RESULT, dict):
result_type = 'dict'
elif isinstance(RESULT, str) and len(RESULT) != 0:
result_type = 'str'

# Set Flags
ran_flags = False
ran_commands = False
ran_plain = False

# Display based on type:
if result_type is 'dict':
# Print Out: flags
if 'flags' in RESULT:
ran_flags = True
print("Flags:" + RESULT['flags'])

# Print Out: commands
if 'commands' in RESULT:
ran_commands = True
print("Commands:" + RESULT['commands'])
sys.exit()
elif result_type is 'str':
# Print Out: Plain text
if len(RESULT) != 0:
ran_plain = True
print(RESULT)
sys.exit()

# No Results
print('No information returned from: $%s.%s' % (ARG_SERVICE, ARG_COMMAND))
sys.exit()
56 changes: 56 additions & 0 deletions install.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#!/usr/bin/env python
import sys
import os

# @ TODO Thoughts:
# ----------------
# Install to /usr/local/bin/hlp, otherwise probably:
# I don't think it should be here, it's just a removable CLI tool
#
# For PIP Package: Install to ~/.local/lib/python2.X/sites-packages
# I don't think it needs to be PIP
#
# For Friendly Use:
# ln -s /where-its-located/cmd_help.py /local/usr/bin/cmd_help
# or
# ln -s /where-its-located/cmd_help.py /local/usr/bin/hlp
# or
# .bashrc alias hlp='/location/cmd_help.py $1 $2' but then it's limited
# to two args if it's upgraded.

# Allows the path to iterate
SYSTEM_PATH = sys.path
sorted(SYSTEM_PATH)
SYSTEM_PATH.pop(0)

# User HOME Path
PATH_HOME = os.environ['HOME']

# Get Python Version
MAJOR = sys.version_info[0]
MINOR = sys.version_info[1]
MICRO = sys.version_info[2]

PYTHON_VERSION = "python%s.%s" % (MAJOR, MINOR)

# See if Install Path exists
INSTALL_PATH = "%s/.local/lib/%s/site-packages/" % (PATH_HOME, PYTHON_VERSION)


# Check the PATH variable
if INSTALL_PATH not in SYSTEM_PATH:
print "Error, missing the following in PATH:\n %s" % INSTALL_PATH
print "\nYour PATH contains:"
print "\n ".join(sys.path)
sys.exit(0)

# Check for path
if not os.path.exists(INSTALL_PATH):
print "Error, could locate and install to %s" % INSTALL_PATH
sys.exit(0)


# Install To Path
# @ TODO here
#
# ...
149 changes: 149 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
# CLI Snippet Tool
This is a Python 2.6/2.7 package to be used in your command line to easily assist you with your favorite snippets.

_[Soon to be Python3 compatible as well.]_

> **STATUS**: In Development
<!-- TOC -->

- [CLI Snippet Tool](#cli-snippet-tool)
- [Save Development Time](#save-development-time)
- [Definitions](#definitions)
- [Custom Topics](#custom-topics)
- [Rules to Topics](#rules-to-topics)
- [Writing your Topic](#writing-your-topic)
- [Road Map & Contributing](#road-map--contributing)

<!-- /TOC -->

## Save Development Time

Although there are Linux `man`(ual) pages and many `--help` flags, even the most seasoned developers forget many commands and at times simply cannot recall.

Most of us turn to Google, yet it's sometimes tedious to find our solution more than once.

The greatest benefit is that you can build your own snippet library easily within your terminal and access it from your terminal on any Linux OS!

> **Fork**: Feel free to fork and customize to your liking. I highly recommend you keep it in your own git repository to transfer it from different computers and servers.

## Definitions

- **TOPICS**: Where methods define help instructions
- **SERVICE**: The first command you want information about (eg: git, find, etc)
- **COMMAND**: The second command to look up with a service, for example:
- `./cli-aid.py <service> <command>`
- `./cli-aid.py git submodule`
- **MODULE**: There is only one module: `topics`, which stores all of your items.


## Custom Topics

Adding a topic is very easy. You should look at `topics/demo.py` for an example. To se the output in action, try these three commands:

```sh
./cli-aid.py demo basic ; A text output
./cli-aid.py demo standard ; A dictionary output
./cli-aid.py demo wrong ; An error output
```


## Rules to Topics

- The topic/**filename** will be the first argument
- The topic/**filename** methods can be used as a second argument
- Topics must always return something, valid options:
- String
- Dictionary in the format of: `{'flags': '..', 'commands': '...'}`


## Writing your Topic

If I wanted to create an example topic I would first figure out the commands I want to remember. So for mysql I may want to be able to type:

```sh
./cli-aid.py mysql connect
./cli-aid.py mysql tricks
```

To accomplish this is very easy:

```sh
touch topics/mysql.py
```

Edit the new file let's define our second arguments, I'll provide the basic (string) and standard (dictionary) output examples.

> **Remember**: You can put any output in these you want, it's for you to help yourself.
```py
def connect():
"""This is a standard dictionary return."""
return {
'flags': """
-u --user
-p --password[=name]
-P --port=#
-v --verbose
""",
'commands': """
mysql -u root -p
mysql -u root -p -h localhost
"""
}

def tricks():
"""This is a basic string return."""
return """
user@localhost limits to the same server
user@% allows remote connections
"""
```

That's it, now you should be able to run it, try it out!

```sh
./cli-aid.py mysql connect
./cli-aid.py mysql tricks
```


## Road Map & Contributing

If you have the desire to contribute the goal to keep in mind is this:

- The code should be extremely simple.
- There should be no third-party addons for the users benefit.
- Would like to do/Plans:
- Unit Testing
- Should user have ability to easily create new topics/details? For example:
- `./cli-aid.py save java install "This is how to install java, etc."` (save would create/update)
- `./cli-aid.py save nginx config "flags: -y auto yes"`
- `./cli-aid.py save nginx config "commands: Anything here like a textfield"`
- The above seems hard to format in one line unless it's basic text. However, using the save method could keep adding to the same file, but removing items would be problematic with string searching to the exact wording they wrote in the past.
- I think if the user is using CLI they are good enough to simply `vim topics/their-file.py`.
- More/Better Error Proofing
- Possibly a better syntax or format for the topic files
- Python 3 compatible
- One argument produces a list of method names within the topic (module).
- A nice shortname rather than `cli-aid`
- Some name ideas:
- `snippette` (too long)
- `snipr` (too much typing, sounds like sniper)
- `scrap` (sounds like garbage, or close to scraper)
- `hlp` (I kind of like, easy to type and remember, something to do with 'help' seems best)
- `assist` (seems nice, like when typing `assist mysql connect` )
- `aid` (I really like this, `aid php config`, may be under the [id-utils](https://www.gnu.org/software/idutils/manual/idutils.html) package though has this alias which runs `lid -ils` )
- maybe even `cli-aid`, `cli-aid find list`
- `ayd` (sounds like aid, not as easy to type)
- `hh` (short to type, might fight with an alias, also doesn't explain much)
- Complete the Install Script, so it can be run from a nice name, eg: `$ hlp js snippets` with out disrupting any other system commands or common words.
- Any ideas are also welcomed, just create a Git Issue!



---
License: MIT

&copy;2017 Jesse Boyer &mdash; [JREAM](http://jream.com)
Empty file added topics/__init__.py
Empty file.
26 changes: 26 additions & 0 deletions topics/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""Demo Helper."""


def basic():
"""Basic output string."""
return """
We can return a single string, use three quotes \"\"\"
For a multiline output!
"""

def standard():
"""Standard output dictionary."""
return {
'flags': """
-x Fake flag example
-d Another flag example
""",
'commands': """
This a dictionary output which has "flags" and "commands".
It still outputs a multiline item but it's separated more.
"""
}

def wrong():
"""Wrong way, does not return string or dictionary."""
return None
30 changes: 30 additions & 0 deletions topics/git.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""Git Helper."""


def submodule():
"""Submodule."""
return {
'flags': """
-q for --quiet | Only print error messages
-f for --force | only with add, deinit and update
""",
'commands': """
> For new instantiations
git submodule init
git submodule add [email protected]/user/assets.git assets
git submodule update
> Updating a submodule
cd assets
git pull
> Remove a Submodule
git rm -rf assets
git rm --cached doctrine
.. Also remove the entire block from .git/submodules
[submodule "assets"]
> Misc
git submodule status
"""
}

0 comments on commit 4fac893

Please sign in to comment.