Skip to content

Commit

Permalink
Merge pull request #9 from Gaareth/add-config-and-force-option
Browse files Browse the repository at this point in the history
Add a config file and a force option to overwrite profiles
  • Loading branch information
Prayag2 authored Mar 5, 2021
2 parents 57e3971 + bec4f98 commit 066f3a4
Show file tree
Hide file tree
Showing 11 changed files with 113 additions and 43 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ README.md
env
Konsave.egg-info
build
dist
dist
__pycache__/
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ A CLI program that will let you save and apply your KDE Plasma customizations wi

---
## Dependencies
There are no dependencies! Just make sure your python version is above `3.9`.
There is only `PyYaml` as dependency, which will be installed automatically by pip.
Also make sure your python version is above `3.9`.

## Installation
Install from PyPI
Expand All @@ -18,6 +19,8 @@ Install from PyPI
`konsave -h` or `konsave --help`
### Save current configuration as a profile
`konsave -s <profile name>` or `konsave --save <profile name>`
### Overwrite an already saved profile
`konsave -s <profile name> -f` or `konsave -s <profile name> --force `
### List all profiles
`konsave -l` or `konsave --list`
### Remove a profile
Expand Down
36 changes: 19 additions & 17 deletions konsave/__main__.py
Original file line number Diff line number Diff line change
@@ -1,44 +1,46 @@
## IMPORT ##
import os, argparse
import argparse
from konsave.funcs import *


## MAIN ##
def main():

## PARSER SETTINGS ##
parser = argparse.ArgumentParser(
prog = 'Konsave',
epilog = "Please report bugs at https://www.github.com/prayag2/konsave"
prog='Konsave',
epilog="Please report bugs at https://www.github.com/prayag2/konsave"
)

## ADDING ARGS ##
parser.add_argument('-l', '--list', required = False, action = 'store_true', help='Lists created profiles')
parser.add_argument('-s', '--save', required = False, type = str, help='Save current config as a profile', metavar = '<name>')
parser.add_argument('-r', '--remove', required = False, type = int, help='Remove the specified profile', metavar = '<id>')
parser.add_argument('-a', '--apply', required = False, type = int, help='Apply the specified profile', metavar = '<id>')
parser.add_argument('-e', '--export-profile', required = False, type = int, help='Export a profile and share with your friends!', metavar = '<id>')
parser.add_argument('-i', '--import-profile', required = False, type = str, help='Import a konsave file', metavar = '<path>')
parser.add_argument('-l', '--list', required=False, action='store_true', help='Lists created profiles')
parser.add_argument('-s', '--save', required=False, type=str, help='Save current config as a profile',
metavar='<name>')
parser.add_argument('-r', '--remove', required=False, type=int, help='Remove the specified profile', metavar='<id>')
parser.add_argument('-a', '--apply', required=False, type=int, help='Apply the specified profile', metavar='<id>')
parser.add_argument('-e', '--export-profile', required=False, type=int,
help='Export a profile and share with your friends!', metavar='<id>')
parser.add_argument('-i', '--import-profile', required=False, type=str, help='Import a konsave file',
metavar='<path>')
parser.add_argument('-f', '--force', required=False, action='store_true', help='Overwrite already saved profiles')

## PARSING ARGS ##
args = parser.parse_args()

## CHECKING FOR ARGUMENTS ##
if args.list:
check_error(list_profiles, list_of_profiles, length_of_lop)
elif args.save != None:
check_error(save_profile, args.save, list_of_profiles)
elif args.remove != None:
elif args.save is not None:
check_error(save_profile, args.save, list_of_profiles, args.force)
elif args.remove is not None:
check_error(remove_profile, args.remove, list_of_profiles, length_of_lop)
elif args.apply != None:
elif args.apply is not None:
check_error(apply_profile, args.apply, list_of_profiles, length_of_lop)
elif args.export_profile != None:
elif args.export_profile is not None:
check_error(export, args.export_profile, list_of_profiles, length_of_lop)
elif args.import_profile != None:
elif args.import_profile is not None:
check_error(import_profile, args.import_profile)
else:
parser.print_help()



## CALLING MAIN ##
Expand Down
Binary file modified konsave/__pycache__/__init__.cpython-39.pyc
Binary file not shown.
Binary file modified konsave/__pycache__/__main__.cpython-39.pyc
Binary file not shown.
Binary file modified konsave/__pycache__/funcs.cpython-39.pyc
Binary file not shown.
Binary file modified konsave/__pycache__/vars.cpython-39.pyc
Binary file not shown.
28 changes: 28 additions & 0 deletions konsave/conf.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
entries:
- gtk-2.0
- gtk-3.0
- gtk-4.0
- Kvantum
- latte
- dolphinrc
- konsolerc
- kcminputrc
- kdeglobals
- kglobalshortcutsrc
- klipperrc
- krunnerrc
- kscreenlockerrc
- ksmserverrc
- kwinrc
- kwinrulesrc
- plasma-org.kde.plasma.desktop-appletsrc
- plasmarc
- plasmashellrc
- gtkrc
- gtkrc-2.0
- lattedockrc
- breezerc
- oxygenrc
- lightlyrc
- ksplashrc
73 changes: 54 additions & 19 deletions konsave/funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@
from zipfile import is_zipfile, ZipFile
from konsave.vars import *

from pkg_resources import resource_stream, resource_filename

try:
import yaml
except ModuleNotFoundError:
raise ModuleNotFoundError("Please install the module PyYAML using pip: \n"
"pip install PyYAML")


## FUNCTIONS ##
def mkdir(path):
'''
Expand All @@ -14,12 +23,38 @@ def mkdir(path):
return path


def load_config():
"""
Load the yaml file which contains the files and folder to be saved
The file should be formatted like this:
---
entries:
- folder name
- file name
- another file name
- another folder name
"""
default_config_path = resource_filename('konsave', 'conf.yaml')
if not os.path.exists(CONFIG_FILE):
print_msg(f"No config file found! Using default config ({default_config_path}).")
shutil.copy(default_config_path, CONFIG_FILE)
print_msg(f"Saved default config to: {CONFIG_FILE}")
return yaml.load(resource_stream('konsave', 'conf.yaml'), Loader=yaml.FullLoader)["entries"]

with open(CONFIG_FILE) as file:
config = yaml.load(file, Loader=yaml.FullLoader)
return config["entries"]


# PARSE AND SEARCH IN A CONFIG FILE
def search_config(path, section, option):
'''
This function will parse config files and search for specific values
'''
config = configparser.ConfigParser(strict = False)
config = configparser.ConfigParser(strict=False)
config.read(path)
return config[section][option]

Expand Down Expand Up @@ -69,31 +104,31 @@ def list_profiles(list_of_profiles, length_of_lop):
print("Konsave profiles:")
print(f"ID\tNAME")
for i, item in enumerate(list_of_profiles):
print(f"{i+1}\t{item}")
print(f"{i + 1}\t{item}")


# SAVE PROFILE
def save_profile(name, list_of_profiles):
def save_profile(name, list_of_profiles, force=False):
'''
Saves necessary config files in ~/.config/konsave/profiles/<name>
'''

# assert
assert (name not in list_of_profiles), "Profile with this name already exists"
assert (name not in list_of_profiles or force), "Profile with this name already exists"

# run
print_msg("saving profile...")
PROFILE_DIR = os.path.join(PROFILES_DIR, name)
mkdir(PROFILE_DIR)

for folder in folder_names:
source = os.path.join(CONFIG_DIR, folder)
if os.path.exists(source):
shutil.copytree(source, f"{PROFILE_DIR}/{folder}")
for file in file_names:
source = os.path.join(CONFIG_DIR, file)

entries = load_config()
for entry in entries:
source = os.path.join(CONFIG_DIR, entry)
if os.path.exists(source):
shutil.copy(source, PROFILE_DIR)
if os.path.isdir(source):
shutil.copytree(source, f"{PROFILE_DIR}/{entry}", dirs_exist_ok=True)
else:
shutil.copy(source, PROFILE_DIR)

print_msg('Profile saved successfully!')

Expand All @@ -103,7 +138,7 @@ def apply_profile(id, list_of_profiles, length_of_lop):
'''
Applies profile of the given id
'''

# Lowering id by 1
id -= 1

Expand Down Expand Up @@ -185,7 +220,7 @@ def check_path_and_copy(path1, path2, export_location, name):
shutil.copytree(path2, os.path.join(export_location, name), dirs_exist_ok=True)
else:
print_msg(f"Couldn't find {path1} or {path2}. Skipping...")

check_path_and_copy(LOCAL_ICON_DIR, USR_ICON_DIR, ICON_EXPORT_PATH, icon)
check_path_and_copy(LOCAL_CURSOR_DIR, USR_CURSOR_DIR, CURSOR_EXPORT_PATH, cursor)
shutil.copytree(PLASMA_DIR, PLASMA_EXPORT_PATH, dirs_exist_ok=True)
Expand All @@ -203,10 +238,10 @@ def import_profile(path):
'''
This will import an exported profile
'''

# assert
assert (is_zipfile(path) and path[-5:] == export_extension), "Not a valid konsave file"
item = os.path.basename(path)[:-5]
item = os.path.basename(path)[:-5]
assert (not os.path.exists(os.path.join(PROFILES_DIR, item))), "A profile with this name already exists"

# run
Expand Down Expand Up @@ -235,7 +270,7 @@ def import_profile(path):
shutil.copytree(PLASMA_IMPORT_PATH, PLASMA_DIR, dirs_exist_ok=True)
shutil.copytree(ICON_IMPORT_PATH, LOCAL_ICON_DIR, dirs_exist_ok=True)
shutil.copytree(CURSOR_IMPORT_PATH, LOCAL_CURSOR_DIR, dirs_exist_ok=True)

shutil.rmtree(TEMP_PATH)

print_msg("Profile successfully imported!")
print_msg("Profile successfully imported!")
5 changes: 2 additions & 3 deletions konsave/vars.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,12 @@
CONFIG_DIR = os.path.join(HOME, '.config')
KONSAVE_DIR = os.path.join(CONFIG_DIR, 'konsave')
PROFILES_DIR = os.path.join(KONSAVE_DIR, 'profiles')
CONFIG_FILE = os.path.join(KONSAVE_DIR, "conf.yaml")

folder_names = ['gtk-2.0', 'gtk-3.0', 'gtk-4.0', 'Kvantum', 'latte']
file_names = ['dolphinrc', 'konsolerc', 'kcminputrc', 'kdeglobals', 'kglobalshortcutsrc', 'klipperrc', 'krunnerrc', 'kscreenlockerrc', 'ksmserverrc', 'kwinrc', 'kwinrulesrc', 'plasma-org.kde.plasma.desktop-appletsrc', 'plasmarc', 'plasmashellrc', 'gtkrc', 'gtkrc-2.0', 'lattedockrc', 'breezerc', 'oxygenrc', 'lightlyrc', 'ksplashrc']
export_extension = '.knsv'

if not os.path.exists(PROFILES_DIR):
os.mkdirs(PROFILES_DIR)
os.mkdir(PROFILES_DIR)

list_of_profiles = os.listdir(PROFILES_DIR)
length_of_lop = len(list_of_profiles)
6 changes: 4 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@ def read_desc():

setup (
name="Konsave",
version="1.0.3",
version="1.0.4",
author="Prayag Jain",
author_email="prayagjain2@gmail.com",
description = "A program that lets you save your Plasma configuration in an instant!",
long_description=read_desc(),
long_description_content_type="text/markdown",
url="https://www.github.com/prayag2/konsave/",
packages=find_packages(),
package_data={'config': ['conf.yaml']},
install_requires=['PyYaml'],
classifiers = [
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
"Operating System :: POSIX",
Expand All @@ -26,4 +28,4 @@ def read_desc():
"konsave = konsave.__main__:main"
]
}
)
)

0 comments on commit 066f3a4

Please sign in to comment.