]> Nutra Git (v2) - nutratech/cli.git/commitdiff
wip stuff 4/head
authorShane Jaroch <chown_tee@proton.me>
Tue, 12 Jul 2022 15:39:20 +0000 (11:39 -0400)
committerShane Jaroch <chown_tee@proton.me>
Tue, 12 Jul 2022 19:09:49 +0000 (15:09 -0400)
make install use pip install --user

nvm

try going from scripts to entry_points

try both

os specific setup.py, don't lint scripts/ or nutra

bump version, rename to CHANGELOG.rst

make build also does clean (via _build)

add n as script too, shorthand

install wheel as part of install

try better graft

try this, explicit include

explicit exclude?

try this, and update submodule

oops

add .env.bat

adjust changelog

use new db submodule

fix test

20 files changed:
.env.bat [new file with mode: 0644]
.gitignore
MANIFEST.in
Makefile
README.rst
ntclient/CHANGELOG.md [deleted file]
ntclient/CHANGELOG.rst [new file with mode: 0644]
ntclient/__init__.py
ntclient/__main__.py
ntclient/ntsqlite
ntclient/persistence/__init__.py
ntclient/persistence/sql/__init__.py
ntclient/persistence/sql/nt/funcs.py
ntclient/services/recipe.py
ntclient/utils/__init__.py
requirements-test-win_xp-ubu1604.txt [moved from tests/requirements-win_xp-ubu1604.txt with 100% similarity]
requirements-test.txt [moved from tests/requirements.txt with 100% similarity]
scripts/n [moved from scripts/nutra.py with 100% similarity]
setup.py
tests/test_cli.py

diff --git a/.env.bat b/.env.bat
new file mode 100644 (file)
index 0000000..4db2110
--- /dev/null
+++ b/.env.bat
@@ -0,0 +1 @@
+set PY_SYS_INTERPRETER=python3
index c99d0b37185fbc1e46b36777796057aaf02f39d9..a57656af3a3cdbd9e28c82ffa0c1135becddc605 100644 (file)
@@ -9,6 +9,7 @@
 .idea/
 __sha__.py
 *.sqlite
+.nutra*
 
 ####################
 ## Python Ignores ##
index da653db6228174538d01c30fa02f6b40358e3bf0..1345ae8acd7209b152dd132ce9656b5419e7fbbe 100644 (file)
@@ -2,13 +2,15 @@ include requirements.txt
 include requirements-*.txt
 
 include ntclient/LICENSE
-include ntclient/CHANGELOG.md
+include ntclient/CHANGELOG.rst
 
 include ntclient/ntsqlite/LICENSE
 include ntclient/ntsqlite/README.rst
-include ntclient/ntsqlite/CHANGELOG.md
-graft ntclient/ntsqlite/sql/
+include ntclient/ntsqlite/CHANGELOG.rst
+include ntclient/ntsqlite/sql/*.sql
+include ntclient/ntsqlite/sql/data/*.csv
+include ntclient/ntsqlite/sql/upgrade_scripts/*.sql
 
-global-exclude *.sqlite3
+global-exclude nt.sqlite3
 
 global-exclude __pycache__/*
index 4fa657eae40608ce63a7f67bedba1dc401662b7c..fef247ab670bf083bd990c030660146871b17f3d 100644 (file)
--- a/Makefile
+++ b/Makefile
@@ -16,7 +16,7 @@ _help:
 init:  ## Set up a Python virtual environment
        git submodule update --init
        if [ ! -d .venv ]; then \
-               /usr/bin/python3 -m venv .venv; \
+               $(PY_SYS_INTERPRETER) -m venv .venv; \
        fi
        - direnv allow
        @echo -e "\r\nNOTE: activate venv, and run 'make deps'\r\n"
@@ -35,18 +35,23 @@ _venv:
 # Install requirements
 # ---------------------------------------
 
-PIP := python -m pip
+PY_SYS_INTERPRETER ?= /usr/bin/python3
+PY_VIRTUAL_INTERPRETER ?= python
+
+PIP ?= $(PY_VIRTUAL_INTERPRETER) -m pip
+
 REQ_OPT := requirements-optional.txt
 REQ_LINT := requirements-lint.txt
-REQ_TEST := tests/requirements.txt
-REQ_OLD := tests/requirements-win_xp-ubu1604.txt
+REQ_TEST := requirements-test.txt
+REQ_OLD := requirements-test-win_xp-ubu1604.txt
+
 .PHONY: _deps
 _deps:
        $(PIP) install wheel
        $(PIP) install -r requirements.txt
        - $(PIP) install -r $(REQ_OPT)
        - $(PIP) install -r $(REQ_LINT)
-       - $(PIP) install -r $(REQ_TEST) || (echo "\r\nTEST REQs failed... try old version" && $(PIP) install -r $(REQ_OLD))
+       - $(PIP) install -r $(REQ_TEST) || (echo "\r\nTEST REQs failed. Trying old version" && $(PIP) install -r $(REQ_OLD))
 
 .PHONY: deps
 deps: _venv _deps      ## Install requirements
@@ -63,7 +68,7 @@ format:
        black $(LINT_LOCS)
 
 
-LINT_LOCS := ntclient/ tests/ scripts/ nutra setup.py
+LINT_LOCS := ntclient/ tests/ setup.py
 YAML_LOCS := ntclient/ntsqlite/.*.yml .github/workflows/ .*.yml
 # NOTE: yamllint       ntclient/ntsqlite/.travis.yml ? (submodule)
 # NOTE: doc8           ntclient/ntsqlite/README.rst  ? (submodule)
@@ -107,39 +112,31 @@ test: _venv _test ## Run CLI unittests
 
 .PHONY: ntsqlite/build
 ntsqlite/build:
-       python ntclient/ntsqlite/sql/__init__.py
+       $(PY_SYS_INTERPRETER) ntclient/ntsqlite/sql/__init__.py
 
 # TODO: nt-sqlite/test
 
 
 # ---------------------------------------
-# Python build stuff
+# Python build & install
 # ---------------------------------------
 
 .PHONY: _build
 _build:
-       python setup.py --quiet sdist
+       $(PY_SYS_INTERPRETER) setup.py --quiet sdist
 
 .PHONY: build
-build: _venv _build clean      ## Create sdist binary *.tar.gz
-
-.PHONY: _install
-_install:
-       python -m pip install wheel
-       python -m pip install .
-       python -m pip show nutra
-       - python -c 'import shutil; print(shutil.which("nutra"));'
-       nutra -v
+build: ## Create sdist binary *.tar.gz
+build: _build clean
 
-.PHONY: install
-install: _venv _install        ## pip install nutra
-
-.PHONY: _uninstall
-_uninstall:
-       python -m pip uninstall -y nutra
 
-.PHONY: uninstall
-uninstall: _venv _uninstall    ## pip uninstall nutra
+.PHONY: install
+install:       ## pip install nutra
+       $(PY_SYS_INTERPRETER) -m pip install wheel
+       $(PY_SYS_INTERPRETER) -m pip install .
+       $(PY_SYS_INTERPRETER) -m pip show nutra
+       - $(PY_SYS_INTERPRETER) -c 'import shutil; print(shutil.which("nutra"));'
+       nutra -v
 
 
 # ---------------------------------------
index 6072726a0ef1b772682dae3ecf6975c97d6be073..1c2c8bcedc6122829da73895f824c6cc8f62c577 100644 (file)
@@ -24,9 +24,9 @@ Extensible command-line tools for nutrient analysis.
 
 *Requires:*
 
-- Python 3.4.0 or later (lzma, ssl & sqlite3 modules) [Win XP / Ubuntu 16.04]
-- Packages: see ``setup.py``, ``requirements.txt``, and ``config`` folder
-- Internet connection, to download food database & package dependencies
+- Python 3.4.0 or later (lzma, ssl & sqlite3 modules) [Win XP / Ubuntu 16.04].
+- Packages: see ``setup.py``, and ``requirements.txt`` files.
+- Internet connection, to download food database & package dependencies.
 
 See nt database:   https://github.com/nutratech/nt-sqlite
 
diff --git a/ntclient/CHANGELOG.md b/ntclient/CHANGELOG.md
deleted file mode 100644 (file)
index c690c1d..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-# Changelog
-
-All notable changes to this project will be documented in this file.
-
-The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
-and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
-
-## [Unreleased]
-
-### Added
-
--   Download cache & checksum verification
--   Basic functionality of `import` and `export` subcommands
--   `[DEVELOPMENT]` Added `Makefile` with easy commands for `init`, `lint`, `test`, etc
-
-## [0.2.2] - 2022-04-08
-
-### Added
-
--   Limit search & sort results to top `n` results (e.g. top 10 or top 100)
--   Enhanced terminal sizing (buffer termination)
--   Pydoc PAGING flag via `--no-pager` command line arg (with `set_flags()` method)
--   Check for appropriate `ntsqlite` database version
--   `[DEVELOPMENT]` Special `file_or_dir_path` and `file_path` custom type validators
-    for argparse
--   `[DEVELOPMENT]` Added special requirements files for
-    (`test`, `lint`, `optional` [Levenshtein], and `win_xp-test` [Python 3.4])
--   `[DEVELOPMENT]` Added `CHANGELOG.md` file
-
-### Changed
-
--   Print `exit_code` in DEBUG mode (`--debug` flag/arg)
--   Moved `subparsers` module in `ntclient.argparser` to `__init__`
--   Moved tests out of `ntclient/` and into `tests/` folder
-
-## [0.2.1] - 2021-05-30
-
-### Added
-
--   Python 3.4.3 support (Windows XP and Ubuntu 16.04)
--   Debug flag (`--debug | -d`) for all commands
-
-### Changed
-
--   Overall structure with main file and argparse methods
--   Use soft pip requirements `~=` instead of `==`
--   `DEFAULT` and `OVER` colors
-
-### Removed
-
--   guid columns from `ntsqlite` submodule
-
-## [0.2.0] - 2021-05-21
-
-### Added
-
--   SQLite support for `usda` and `nt` schemas (removed API calls to remote server)
--   Preliminary support for `recipe` and `bio` subcommands
--   On-boarding process with `init` subcommand
--   Support for `argcomplete` on `bash` (Linux/macOS)
--   Tests
-
-## [0.0.38] - 2020-08-01
-
-### Added
-
--   Support for analysis of day CSV files
diff --git a/ntclient/CHANGELOG.rst b/ntclient/CHANGELOG.rst
new file mode 100644 (file)
index 0000000..d60c838
--- /dev/null
@@ -0,0 +1,122 @@
+***********
+ Changelog
+***********
+
+All notable changes to this project will be documented in this file.
+
+The format is based on `Keep a Changelog <https://keepachangelog.com/en/1.1.0/>`_,
+and this project adheres to `Semantic Versioning <https://semver.org/spec/v2.0.0.html>`_.
+
+
+
+[Unreleased]
+########################################################################
+
+Added
+~~~~~
+
+- Basic functionality of ``import`` and ``export`` sub-commands
+
+
+
+[0.2.3] - 2022-07-12
+########################################################################
+
+Added
+~~~~~
+
+- ``[WIP]`` Download cache & checksum verification
+- ``[DEVELOPMENT]`` Added ``Makefile`` with easy commands for ``init``,
+  ``lint``, ``test``, etc
+- ``n`` as a shorthand script for ``nutra``
+
+Changed
+~~~~~~~
+
+- Rename to ``CHANGELOG.rst``
+
+Fixed
+~~~~~
+
+- Separate installer logic ``scripts`` & ``entry_points`` for Windows vs. Unix.
+
+Removed
+~~~~~~~
+
+- Some tables, e.g. ``biometric``. See ``nt-sqlite`` submodule for details.
+  This is still a work in progress to newer tables.
+
+
+
+[0.2.2] - 2022-04-08
+########################################################################
+
+Added
+~~~~~
+
+- Limit search & sort results to top ``n`` results (e.g. top 10 or top 100)
+- Enhanced terminal sizing (buffer termination)
+- ``Pydoc`` ``PAGING`` flag via ``--no-pager`` command line arg
+  (with ``set_flags()`` method)
+- Check for appropriate ``ntsqlite`` database version
+- ``[DEVELOPMENT]`` Special ``file_or_dir_path`` and ``file_path``
+  custom type validators for ``argparse``
+- ``[DEVELOPMENT]`` Added special requirements files for
+  (``test``, ``lint``, ``optional: Levenshtein``,
+  and ``win_xp-test`` [Python 3.4])
+- ``[DEVELOPMENT]`` Added ``CHANGELOG.md`` file
+
+Changed
+~~~~~~~
+
+- Print ``exit_code`` in DEBUG mode (`--debug` flag/arg)
+- Moved ``subparsers`` module in ``ntclient.argparser`` to ``__init__``
+- Moved tests out of ``ntclient/`` and into ``tests/`` folder
+
+
+
+[0.2.1] - 2021-05-30
+########################################################################
+
+Added
+~~~~~
+
+- Python 3.4 support (Windows XP and Ubuntu 16.04)
+- Debug flag (``--debug | -d``) for all commands
+
+Changed
+~~~~~~~
+
+- Overall structure with main file and argparse methods
+- Use soft pip requirements ``~=`` instead of ``==``
+- ``DEFAULT`` and ``OVER`` colors
+
+Removed
+~~~~~~~
+
+- ``guid`` columns from ``ntsqlite`` submodule
+
+
+
+[0.2.0] - 2021-05-21
+########################################################################
+
+Added
+~~~~~
+
+- SQLite support for ``usda`` and ``nt`` schemas
+  (removed API calls to remote server)
+- Preliminary support for ``recipe`` and ``bio`` subcommands
+- On-boarding process with ``init`` subcommand
+- Support for ``argcomplete`` on ``bash`` (Linux/macOS)
+- Tests
+
+
+
+[0.0.38] - 2020-08-01
+########################################################################
+
+Added
+~~~~~
+
+- Support for analysis of day CSV files
index 366b00a510cc73ae77194e6c9221685bde4a78aa..57717f85596c28c9be816a524e96589a42633416 100755 (executable)
@@ -35,9 +35,9 @@ from ntclient.ntsqlite.sql import NT_DB_NAME
 
 # Package info
 __title__ = "nutra"
-__version__ = "0.2.3.dev1"
+__version__ = "0.2.3"
 __author__ = "Shane Jaroch"
-__email__ = "nutratracker@gmail.com"
+__email__ = "chown_tee@proton.me"
 __license__ = "GPL v3"
 __copyright__ = "Copyright 2018-2022 Shane Jaroch"
 __url__ = "https://github.com/nutratech/cli"
@@ -45,12 +45,13 @@ __url__ = "https://github.com/nutratech/cli"
 # Sqlite target versions
 __db_target_nt__ = "0.0.5"
 __db_target_usda__ = "0.0.8"
+USDA_XZ_SHA256 = "25dba8428ced42d646bec704981d3a95dc7943240254e884aad37d59eee9616a"
 
 # Global variables
 ROOT_DIR = os.path.abspath(os.path.dirname(__file__))
-NUTRA_DIR = os.path.join(os.path.expanduser("~"), ".nutra")
+NUTRA_DIR = os.getenv("NUTRA_HOME", os.path.join(os.path.expanduser("~"), ".nutra"))
 USDA_DB_NAME = "usda.sqlite"
-# NT_DB_NAME = "nt.sqlite"  # defined in ntclient.ntsqlite.sql
+# NOTE: NT_DB_NAME = "nt.sqlite3" is defined in ntclient.ntsqlite.sql
 DEBUG = False
 PAGING = True
 
@@ -63,7 +64,7 @@ PY_SYS_VER = sys.version_info[0:3]
 PY_MIN_STR = ".".join(str(x) for x in PY_MIN_VER)
 PY_SYS_STR = ".".join(str(x) for x in PY_SYS_VER)
 if PY_SYS_VER < PY_MIN_VER:
-    print("ERROR: nutra requires Python %s or later to run" % PY_MIN_STR)
+    print("ERROR: %s requires Python %s or later to run" % (__title__, PY_MIN_STR))
     print("HINT:  You're running Python %s" % PY_SYS_STR)
     sys.exit(1)
 
@@ -75,6 +76,7 @@ DEFAULT_RESULT_LIMIT = BUFFER_HT - 4
 
 DEFAULT_DAY_H_BUFFER = BUFFER_WD - 4 if BUFFER_WD > 12 else 8
 
+# TODO: keep one extra row on winXP / cmd.exe, it cuts off
 DECREMENT = 1 if platform.system() == "Windows" else 0
 DEFAULT_SORT_H_BUFFER = (
     BUFFER_WD - (38 + DECREMENT) if BUFFER_WD > 50 else (12 - DECREMENT)
@@ -84,6 +86,21 @@ DEFAULT_SEARCH_H_BUFFER = (
 )
 
 
+# NOTE: wip
+# class CLIConfig:
+#     def __init__(self):
+#         prop1 = True
+#         usda_sqlite
+#         nt_sqlitedriver
+
+
+# TODO:
+#  Nested nutrient tree, like:
+#   http://www.whfoods.com/genpage.php?tname=nutrientprofile&dbid=132
+#  Attempt to record errors in failed try/catch block (bottom of __main__.py)
+#  Make use of argcomplete.warn(msg) ?
+
+
 def set_flags(args: argparse.Namespace) -> None:
     """
     Sets
@@ -93,13 +110,7 @@ def set_flags(args: argparse.Namespace) -> None:
     """
     global DEBUG, PAGING  # pylint: disable=global-statement
     DEBUG = args.debug
-    PAGING = not args.no_paging
+    PAGING = not args.no_pager
 
     if DEBUG:
         print("Console size: %sh x %sw" % (BUFFER_HT, BUFFER_WD))
-
-
-# TODO:
-#  nested nutrient tree, like: http://www.whfoods.com/genpage.php?tname=nutrientprofile&dbid=132
-#  attempt to record errors in failed try/catch block (bottom of __main__.py)
-#  make use of argcomplete.warn(msg) ?
index 8df1b2ef09170640896606f76c2a4430ebd02701..79a35cbea4ebb763c762dd2beb34bc5782b1c9cb 100644 (file)
@@ -9,7 +9,7 @@ This file is part of nutra, a nutrient analysis program.
     https://pypi.org/project/nutra/
 
 nutra is an extensible nutrient analysis and composition application.
-Copyright (C) 2018-2022  Shane Jaroch <nutratracker@gmail.com>
+Copyright (C) 2018-2022  Shane Jaroch <chown_tee@proton.me>
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
@@ -62,10 +62,7 @@ def build_argparser() -> argparse.ArgumentParser:
         "-d", "--debug", action="store_true", help="enable detailed error messages"
     )
     arg_parser.add_argument(
-        "--no-pager",
-        dest="no_paging",
-        action="store_true",
-        help="disable paging (print full output)",
+        "--no-pager", action="store_true", help="disable paging (print full output)"
     )
 
     # Subparsers
@@ -79,7 +76,7 @@ def main(args: list = None) -> int:
     """
     Main method for CLI
 
-    @param args: List[str] | None
+    @param args: List[str]
     """
 
     start_time = time.time()
@@ -99,7 +96,7 @@ def main(args: list = None) -> int:
             persistence_init()
 
             args_dict = dict(vars(parser))
-            for expected_arg in ["func", "debug", "no_paging"]:
+            for expected_arg in ["func", "debug", "no_pager"]:
                 args_dict.pop(expected_arg)
 
             # Run function
@@ -109,7 +106,7 @@ def main(args: list = None) -> int:
 
         # Otherwise print help
         arg_parser.print_help()
-        return 1, None
+        return 0, None
 
     # Build the parser, set flags
     _parser = parse_args()
@@ -118,7 +115,7 @@ def main(args: list = None) -> int:
 
     # TODO: bug reporting?
     # Try to run the function
-    exit_code = None
+    exit_code = 1
     try:
         exit_code, *_results = func(_parser)
         return exit_code
index bd445909c0e6165e82d6f077b3160cf2c07f4aa4..4f9eec211c1073f093411f15e29cb2347534e7cd 160000 (submodule)
@@ -1 +1 @@
-Subproject commit bd445909c0e6165e82d6f077b3160cf2c07f4aa4
+Subproject commit 4f9eec211c1073f093411f15e29cb2347534e7cd
index 014dcc31661e86cc6b657efb348ab69f3c4975e7..d48acaaea2ba15356f880cb50e49429f155a91c5 100644 (file)
@@ -11,7 +11,8 @@ import os
 from ntclient import NUTRA_DIR
 
 # TODO: init, handle when it doesn't exist yet
-# TODO: prompt to create profile if copying default `prefs.json` with PROFILE_ID: -1 (non-existent)
+# TODO: prompt to create profile if copying default `prefs.json` with PROFILE_ID: -1
+#  (non-existent)
 PREFS_FILE = os.path.join(NUTRA_DIR, "prefs.json")
 PREFS = {}
 PROFILE_ID = None
@@ -33,5 +34,6 @@ def persistence_init() -> None:
     PROFILE_ID = PREFS.get("current_user")
     if DEBUG and not PROFILE_ID:
         print(
-            "WARN: ~/.nutra/prefs.json doesn't contain valid PROFILE_ID, proceeding in bare mode"
+            "WARN: ~/.nutra/prefs.json doesn't contain valid PROFILE_ID,"
+            "proceeding in bare mode"
         )
index 807142d54c20f6a8278e3b8173b995d986e77c99..a6ae0b4393ca7acb8ebcabe96fbec024b03c07d1 100644 (file)
@@ -1,10 +1,10 @@
-"""Main SQL persistence module, need to rethink circular imports and shared code"""
+"""Main SQL persistence module, shared between USDA and NT databases"""
 import sqlite3
 
-# FIXME: maybe just use separate methods for calls with vs. without headers
-#  avoid the mypy headaches, and the liberal comments  # type: ignore
-
 
+# ------------------------------------------------
+# Entry fetching methods
+# ------------------------------------------------
 def sql_entries(sql_result: sqlite3.Cursor) -> list:
     """Formats and returns a `sql_result()` for console digestion and output"""
     # TODO: return object: metadata, command, status, errors, etc?
@@ -21,6 +21,9 @@ def sql_entries_headers(sql_result: sqlite3.Cursor) -> tuple:
     return headers, rows
 
 
+# ------------------------------------------------
+# Supporting methods
+# ------------------------------------------------
 def version(con: sqlite3.Connection) -> str:
     """Gets the latest entry from version table"""
 
@@ -41,10 +44,13 @@ def close_con_and_cur(
     con.close()
 
 
+# ------------------------------------------------
+# Main query methods
+# ------------------------------------------------
 def _prep_query(
     con: sqlite3.Connection, query: str, db_name: str, values=None
 ) -> tuple:
-    """@param values: tuple | list | None"""
+    """@param values: tuple | list"""
 
     from ntclient import DEBUG  # pylint: disable=import-outside-toplevel
 
@@ -75,7 +81,7 @@ def _sql(
     db_name: str,
     values=None,
 ) -> list:
-    """@param values: tuple | list | None"""
+    """@param values: tuple | list"""
 
     cur, result = _prep_query(con, query, db_name, values)
 
@@ -93,7 +99,7 @@ def _sql_headers(
     db_name: str,
     values=None,
 ) -> tuple:
-    """@param values: tuple | list | None"""
+    """@param values: tuple | list"""
 
     cur, result = _prep_query(con, query, db_name, values)
 
index bee8fc6fdced07ad16d497c4467f0794dda8e014..783015a59a9baef613a372fa83e29a82cd654923 100644 (file)
@@ -4,8 +4,8 @@ from ntclient.persistence.sql.nt import sql, sql_headers
 
 def sql_nt_next_index(table=None):
     """Used for previewing inserts"""
-    query = "SELECT MAX(id) FROM %s;" % table  # nosec: B608
-    return int(sql(query)[0]["MAX(id)"])
+    query = "SELECT MAX(id) as max_id FROM %s;" % table  # nosec: B608
+    return int(sql(query)[0]["max_id"])
 
 
 ################################################################################
@@ -26,9 +26,9 @@ SELECT
   name,
   COUNT(recipe_id) AS n_foods,
   SUM(grams) AS grams,
-  created
+  recipe.created as created
 FROM
-  recipes
+  recipe
   LEFT JOIN recipe_dat ON recipe_id = id
 GROUP BY
   id;
@@ -45,7 +45,7 @@ SELECT
   food_id,
   grams
 FROM
-  recipes
+  recipe
   INNER JOIN recipe_dat ON recipe_id = id
     AND id = ?;
 """
index 8eb73e243174051ed4751da4a2a0a137889260f6..3bd6f26c7db6081f73136aab7eb133cbf80b44ca 100644 (file)
@@ -84,7 +84,7 @@ def recipe_import(file_path):
 
     if os.path.isfile(file_path):
         # TODO: better logic than this
-        recipe_id = extract_id_from_filename(file_path) or sql_nt_next_index("recipes")
+        recipe_id = extract_id_from_filename(file_path) or sql_nt_next_index("recipe")
         print(recipe_id)
         with open(file_path, encoding="utf-8") as file:
             reader = csv.DictReader(file)
index a6ef41325dbc6e88dc729d25864768ef00d83b33..db8f3aaac5b17069608b002705f069ae39286e32 100644 (file)
@@ -5,6 +5,8 @@ from colorama import Fore
 # Colors and buffer settings
 ################################################################################
 
+# TODO: make configurable in SQLite or prefs.json
+
 THRESH_WARN = 0.7
 COLOR_WARN = Fore.YELLOW
 
similarity index 100%
rename from tests/requirements.txt
rename to requirements-test.txt
similarity index 100%
rename from scripts/nutra.py
rename to scripts/n
index fffe1b85f949509e2b2fd992c505eb1d8d2f0662..845829c5eafb0088078768dc06e2f168b53df42c 100644 (file)
--- a/setup.py
+++ b/setup.py
@@ -13,8 +13,9 @@ from setuptools import find_packages, setup
 
 from ntclient import PY_MIN_STR, __author__, __email__, __title__, __version__
 
-# cd to parent dir of setup.py
-os.chdir(os.path.dirname(os.path.abspath(__file__)))
+os.chdir(os.path.dirname(os.path.realpath(__file__)))
+
+PLATFORM_SYSTEM = platform.system()
 
 CLASSIFIERS = [
     "Environment :: Console",
@@ -41,35 +42,46 @@ CLASSIFIERS = [
     "Programming Language :: Unix Shell",
 ]
 
+# Read me
 with open("README.rst", encoding="utf-8") as file:
     README = file.read()
 
+# Requirements
 with open("requirements.txt", encoding="utf-8") as file:
     REQUIREMENTS = file.read().split()
 
-if platform.system() != "Windows":
-    # python-Levenshtein builds natively on unix, requires vcvarsall.bat or vc++10 on Windows
+if PLATFORM_SYSTEM != "Windows":
+    # python-Levenshtein builds natively on Unix; Windows needs vcvarsall.bat or vc++10
     with open("requirements-optional.txt", encoding="utf-8") as file:
         optional_reqs = file.read().split()
     REQUIREMENTS.extend(optional_reqs)
 
-setup(
-    name=__title__,
-    author=__author__,
-    author_email=__email__,
-    classifiers=CLASSIFIERS,
-    install_requires=REQUIREMENTS,
-    python_requires=">=%s" % PY_MIN_STR,
-    zip_safe=False,
-    packages=find_packages(exclude=["tests"]),
-    include_package_data=True,
-    platforms=["linux", "darwin", "win32"],
-    scripts=glob.glob("scripts/*"),
-    # entry_points={"console_scripts": ["nutra=ntclient.__main__:main"]},
-    description="Home and office nutrient tracking software",
-    long_description=README,
-    long_description_content_type="text/x-rst",
-    url="https://github.com/nutratech/cli",
-    license="GPL v3",
-    version=__version__,
-)
+# Prepare setup() inputs (OS dependent)
+kwargs = {
+    "name": __title__,
+    "author": __author__,
+    "author_email": __email__,
+    "classifiers": CLASSIFIERS,
+    "install_requires": REQUIREMENTS,
+    "python_requires": ">=%s" % PY_MIN_STR,
+    "zip_safe": False,
+    "packages": find_packages(exclude=["tests"]),
+    "include_package_data": True,
+    "platforms": ["linux", "darwin", "win32"],
+    "description": "Home and office nutrient tracking software",
+    "long_description": README,
+    "long_description_content_type": "text/x-rst",
+    "url": "https://github.com/nutratech/cli",
+    "license": "GPL v3",
+    "version": __version__,
+}
+
+if PLATFORM_SYSTEM == "Windows":
+    kwargs["entry_points"] = {
+        "console_scripts": ["nutra=ntclient.__main__:main", "n=ntclient.__main__:main"]
+    }
+else:
+    kwargs["scripts"] = glob.glob("scripts/*")
+
+# Setup method
+setup(**kwargs)
index c61b5af41d361ae05f2699a23f8c76516b8dc59a..555614c124946c2b3ed8486e9ea5a71ad75cdc8e 100644 (file)
@@ -4,6 +4,7 @@ Created on Fri Jan 31 15:19:53 2020
 
 @author: shane
 """
+# pylint: disable=wrong-import-position
 import os
 import sys
 
@@ -28,9 +29,11 @@ from ntclient.persistence.sql.usda import usda_ver
 from ntclient.services import init
 from ntclient.utils.exceptions import SqlInvalidVersionError
 
+TEST_HOME = os.path.dirname(os.path.abspath(__file__))
+os.environ["NUTRA_HOME"] = os.path.join(TEST_HOME, ".nutra.test")
+
 # TODO: integration tests.. create user, recipe, log.. analyze & compare
 arg_parser = build_argparser()
-TEST_HOME = os.path.dirname(os.path.abspath(__file__))
 
 
 def test_000_init():
@@ -78,7 +81,7 @@ def test_300_argparser_debug_no_paging():
     set_flags(args)
 
     assert args.debug is True
-    assert args.no_paging is True
+    assert args.no_pager is True
 
     from ntclient import DEBUG, PAGING  # pylint: disable=import-outside-toplevel
 
@@ -173,7 +176,7 @@ def test_500_main_module():
 
     sys.argv = ["./nutra"]
     code = nt_main()
-    assert code == 1
+    assert code == 0
 
     with pytest.raises(SystemExit) as system_exit:
         nt_main(args=["-h"])