{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "# !cd {c.get('projects_dir')}{c.get('active_project')} && git pull"
      ],
      "metadata": {
        "id": "uRnD1E8cNRm1",
        "executionInfo": {
          "status": "ok",
          "timestamp": 1673965540877,
          "user_tz": 540,
          "elapsed": 623,
          "user": {
            "displayName": "Jaci ss",
            "userId": "10130648813270993501"
          }
        },
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "fa75a22e-6d54-4b11-b77f-ed714adf660c"
      },
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "remote: Enumerating objects: 8, done.\u001b[K\n",
            "remote: Counting objects:  12% (1/8)\u001b[K\rremote: Counting objects:  25% (2/8)\u001b[K\rremote: Counting objects:  37% (3/8)\u001b[K\rremote: Counting objects:  50% (4/8)\u001b[K\rremote: Counting objects:  62% (5/8)\u001b[K\rremote: Counting objects:  75% (6/8)\u001b[K\rremote: Counting objects:  87% (7/8)\u001b[K\rremote: Counting objects: 100% (8/8)\u001b[K\rremote: Counting objects: 100% (8/8), done.\u001b[K\n",
            "remote: Compressing objects:  20% (1/5)\u001b[K\rremote: Compressing objects:  40% (2/5)\u001b[K\rremote: Compressing objects:  60% (3/5)\u001b[K\rremote: Compressing objects:  80% (4/5)\u001b[K\rremote: Compressing objects: 100% (5/5)\u001b[K\rremote: Compressing objects: 100% (5/5), done.\u001b[K\n",
            "remote: Total 8 (delta 3), reused 8 (delta 3), pack-reused 0\u001b[K\n",
            "Unpacking objects:  12% (1/8)   \rUnpacking objects:  25% (2/8)   \rUnpacking objects:  37% (3/8)   \rUnpacking objects:  50% (4/8)   \rUnpacking objects:  62% (5/8)   \rUnpacking objects:  75% (6/8)   \rUnpacking objects:  87% (7/8)   \rUnpacking objects: 100% (8/8)   \rUnpacking objects: 100% (8/8), done.\n",
            "From https://github.com/Jaciss/jai\n",
            "   a0b6a55..88a338f  main       -> origin/main\n",
            "Updating a0b6a55..88a338f\n",
            "Fast-forward\n",
            " notebooks/notebooks_as_features.ipynb | 12 \u001b[32m++++++++\u001b[m\u001b[31m----\u001b[m\n",
            " 1 file changed, 8 insertions(+), 4 deletions(-)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# get environment"
      ],
      "metadata": {
        "id": "YnfrKngMzcW4"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# %%from_template first_cell\n",
        "try:\n",
        "  c\n",
        "except:\n",
        "  c={'resources':{'jai':{}},'use_google_drive':False}\n",
        "  !wget -qO epc.py https://maya.software/epc.txt\n",
        "  import epc\n",
        "  c = epc.do_setup(c)\n",
        "  %run {c.get('nb_dir')}notebooks_as_features.ipynb"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "kXqUqesd0IcI",
        "executionInfo": {
          "status": "ok",
          "timestamp": 1673965560351,
          "user_tz": 540,
          "elapsed": 2052,
          "user": {
            "displayName": "Jaci ss",
            "userId": "10130648813270993501"
          }
        },
        "outputId": "ea34dc01-3332-4e36-f6d6-aa31746c6bb7"
      },
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "2023-01-17 14:25:58 epc INFO     epc.config_dict(c): may be overridden by `c[setting_name]`\n",
            "2023-01-17 05:25:58 epc INFO     log_level: DEBUG\n",
            "2023-01-17 05:25:58 epc INFO     timezone: America/Anchorage\n",
            "2023-01-17 05:25:58 epc INFO     use_google_drive: False\n",
            "2023-01-17 05:25:58 epc INFO     epc: U2FsdGVkX1/xUi/hYJ+V9stP7WV+Y6fTtkJNZoDL8PX4mSWh/CuEAZUz0VI8r/BvrfQztrCI1rPmduBRSJsTLQeD9AKFNjHMNq15V1ArU7CvCVVXvuKgNsDS0aEN2hJoRMXiy4g7YzIB/b45e3vq8/DV/sFFml1GtWeTtIWLeA1c92UNrF8s3MjpvWhYB+GeD1OSQMcS3aoveW7YD8tSigzRkZQqwmoNrHlNdODtNeLq4idK4VsD9mauLGg/mWKitdfbqUi0yULYpg5pRxPMZaIy4sDFdGYbeaHYBaduf36Wr+ak3x6e7rvT7fF04EST3wv7FM54xAxZiyohgUHIyG+5oYBbvcWsKl74GZpoPYqUffxdnnH8VKURHTE28WaXwdsXwj0edbkX3cNcL/aCOdF9pfCcNPJFbRD0LM7E2sF9xYeqyNMhpnBMKWfXex7rEzj2ZRQbxlRy+f+476Vni/Qf2Ixcc/x5vCvAEJgCueD+loXol4oP3O4eDM6Q1FiPxMDOCYGxJ8TCFVb5795vqsmWsKLfa1pOqnPSJ2Id4ayiryeyxtDShRD8fTq0RplfXU7JMKnrCZJNq4CW+rDSRTOy4cHE0S3zy1EbFtPVP3Y4MCCKaWIHa/LVj9LDZSQvYSZO4xZb3Aw+fuvxqI/4Ow==\n",
            "2023-01-17 05:25:58 epc INFO     resources: {'jai': {}}\n",
            "2023-01-17 05:25:58 epc INFO     active_project: jai\n",
            "2023-01-17 05:25:58 epc INFO     projects_dir: /content/\n",
            "2023-01-17 05:25:58 epc INFO     nb_dir: /content/jai/notebooks/\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "bdd_testing_a_notebook.ipynb\tgit_for_colab.ipynb\t     templates\n",
            "bootstrap_a_notebook.ipynb\tjai_utils.ipynb\t\t     vite.ipynb\n",
            "demo_notebook.ipynb\t\tnotebooks_as_features.ipynb\n",
            "encrypted_private_config.ipynb\tsetup_project.ipynb\n",
            "features  LICENSE  notebooks  README.md\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "2023-01-17 05:25:59 git_for_colab INFO     main parent notebook: git_for_colab\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "c"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "AdLoeKigeBxV",
        "executionInfo": {
          "status": "ok",
          "timestamp": 1673965575744,
          "user_tz": 540,
          "elapsed": 289,
          "user": {
            "displayName": "Jaci ss",
            "userId": "10130648813270993501"
          }
        },
        "outputId": "2225e615-0375-46c6-aac4-9bc0ed98d055"
      },
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'log_level': 10,\n",
              " 'timezone': 'America/Anchorage',\n",
              " 'use_google_drive': False,\n",
              " 'epc': 'U2FsdGVkX1/xUi/hYJ+V9stP7WV+Y6fTtkJNZoDL8PX4mSWh/CuEAZUz0VI8r/BvrfQztrCI1rPmduBRSJsTLQeD9AKFNjHMNq15V1ArU7CvCVVXvuKgNsDS0aEN2hJoRMXiy4g7YzIB/b45e3vq8/DV/sFFml1GtWeTtIWLeA1c92UNrF8s3MjpvWhYB+GeD1OSQMcS3aoveW7YD8tSigzRkZQqwmoNrHlNdODtNeLq4idK4VsD9mauLGg/mWKitdfbqUi0yULYpg5pRxPMZaIy4sDFdGYbeaHYBaduf36Wr+ak3x6e7rvT7fF04EST3wv7FM54xAxZiyohgUHIyG+5oYBbvcWsKl74GZpoPYqUffxdnnH8VKURHTE28WaXwdsXwj0edbkX3cNcL/aCOdF9pfCcNPJFbRD0LM7E2sF9xYeqyNMhpnBMKWfXex7rEzj2ZRQbxlRy+f+476Vni/Qf2Ixcc/x5vCvAEJgCueD+loXol4oP3O4eDM6Q1FiPxMDOCYGxJ8TCFVb5795vqsmWsKLfa1pOqnPSJ2Id4ayiryeyxtDShRD8fTq0RplfXU7JMKnrCZJNq4CW+rDSRTOy4cHE0S3zy1EbFtPVP3Y4MCCKaWIHa/LVj9LDZSQvYSZO4xZb3Aw+fuvxqI/4Ow==',\n",
              " 'resources': {'jai': {}},\n",
              " 'active_project': 'jai',\n",
              " 'projects_dir': '/content/',\n",
              " 'nb_dir': '/content/jai/notebooks/',\n",
              " 'cmds': [],\n",
              " 'nb_ip': '172.28.0.2',\n",
              " 'nb_name': 'git_for_colab',\n",
              " 'running_nb': 'git_for_colab',\n",
              " 'nb_path': '1jlYMNlVX3IeJNDNnhSVjt5qR7ahyfueM'}"
            ]
          },
          "metadata": {},
          "execution_count": 2
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Initial Config"
      ],
      "metadata": {
        "id": "zeS_vur-1fHj"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "git_user = epc.get_token('github_user')\n",
        "git_email = epc.get_token('github_email')\n",
        "!git config --global user.email \"{git_email}\"\n",
        "!git config --global user.name \"{git_user}\""
      ],
      "metadata": {
        "id": "qhwmR-Yo086D",
        "executionInfo": {
          "status": "ok",
          "timestamp": 1673968545456,
          "user_tz": 540,
          "elapsed": 5037,
          "user": {
            "displayName": "Jaci ss",
            "userId": "10130648813270993501"
          }
        },
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "99473328-9863-4e6e-d8eb-6d8908a4ce49"
      },
      "execution_count": 16,
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Save pass variable, leave blank to enter each time: \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## nbdime for notebook git diff\n",
        "`git diff` and similar on JSON that has many minute changes is nearly unworkable. This eliminates much of the noise."
      ],
      "metadata": {
        "id": "d4KPkzvDTRJd"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "%%capture nbdime_install_output\n",
        "nv = !which nbdime\n",
        "# print('which nbdime:',str(nv))\n",
        "if str(nv).strip()=='[]':\n",
        "  %pip install nbdime\n",
        "  !nbdime config-git --enable --global"
      ],
      "metadata": {
        "id": "KOOtW40HE_3f"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "%%writefile /root/.jupyter/nbdime_config.json\n",
        "{\n",
        "  \"GitDiff\": {\n",
        "    \"Ignore\": {\n",
        "      \"/cells/*/outputs\": true,\n",
        "      \"/cells/*\":[\"execution_count\"],\n",
        "      \"/cells/*/metadata\": [\"collapsed\", \"autoscroll\", \"deletable\", \"editable\", \"executionInfo\", \"outputId\", \"colab\"]\n",
        "    }\n",
        "  }\n",
        "}"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "1vl1QIHaG4uK",
        "executionInfo": {
          "status": "ok",
          "timestamp": 1673713234709,
          "user_tz": 540,
          "elapsed": 79,
          "user": {
            "displayName": "Jaci ss",
            "userId": "10130648813270993501"
          }
        },
        "outputId": "6f67e8fb-248a-4a5b-86a5-a1b2d0d75823"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Writing /root/.jupyter/nbdime_config.json\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Generic Git Functions"
      ],
      "metadata": {
        "id": "MYxrmbs8z4k4"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import json\n",
        "from google.colab import _message\n",
        "\n",
        "def get_repo_name(): #idx:int=0):\n",
        "  return c.get('active_project')\n",
        "  # try:\n",
        "  #   repo = c['github'][idx]\n",
        "  #   return repo\n",
        "  # except IndexError:\n",
        "  #   logger.error(\"No repo name at c['github'][\"+str(idx)+\"]\")\n",
        "  #   return None\n",
        "\n",
        "# get_repo_name()\n",
        "\n",
        "def git_pull(quiet=False):\n",
        "  repo = c.get('active_project')\n",
        "  if repo is not None:\n",
        "    if quiet is False:\n",
        "      !cd {c['projects_dir']}{repo} && git status\n",
        "    !cd {c['projects_dir']}{repo} && git pull\n",
        "\n",
        "# git_pull()\n",
        "\n",
        "def nb2repo(show_diff=True):\n",
        "  '''this uses projects_dir/active_project/notebooks vs nb_dir to avoid writing\n",
        "  colab notebooks, which are automatically saved; copy colab notebooks to the repo dir'''\n",
        "  repo = c.get('active_project')\n",
        "  \n",
        "  if repo is not None:\n",
        "    repo_dest_dir = c.get('nb_dir').replace('\\ ',' ') #repo+'/'+ \n",
        "    if c['use_google_drive']==True: repo_dest_dir = c['projects_dir']+repo+'/notebooks/'\n",
        "    hate = f\"{repo_dest_dir}{c['running_nb']}.ipynb\"\n",
        "    print('try to write')\n",
        "    print(r\"\"+hate)\n",
        "    activenb = _message.blocking_request('get_ipynb', request='', timeout_sec=5)['ipynb']\n",
        "    with open(hate, 'w') as nb_file:\n",
        "      nb_file.write(json.dumps(activenb,indent=2))\n",
        "    hate = hate.replace(' ','\\ ')\n",
        "    !ls -lart {hate} |tail -1\n",
        "    if show_diff == True:\n",
        "      !cd {c['projects_dir']}{repo} && echo \"\" && git diff --stat && echo -e \"\\033[0m\\n\" && git diff --minimal\n",
        "\n",
        "# nb2repo()\n",
        "\n",
        "def git_commit(message:str='from github colab notebook'):\n",
        "  '''add -A, status w/confirmation, commit'''\n",
        "  repo = get_repo_name()\n",
        "  if repo is not None:\n",
        "    nb2repo() # save current nb\n",
        "    git_pull(True) # pull any changes\n",
        "    !cd {c['projects_dir']}{repo} && git add -A # add or changes\n",
        "    !cd {c['projects_dir']}{repo} && git status # take a look at what we have\n",
        "    print('message:',message)\n",
        "    yn = input('Do you want to commit now? y/N: ')\n",
        "    if yn=='y':\n",
        "      !cd {c['projects_dir']}{repo} && git commit -m \"{message}\"\n",
        "\n",
        "# git_commit()\n",
        "\n",
        "def git_ppush(message:str='from github colab notebook'):\n",
        "  '''add, commit, push all in one'''\n",
        "  repo = c.get('active_project')\n",
        "  if repo is not None:\n",
        "    git_commit(message)\n",
        "    !cd {c['projects_dir']}{repo} && git push\n",
        "\n",
        "# git_ppush('typehinting')\n",
        "\n",
        "def git_nbastatus():\n",
        "  repo = c.get('active_project')\n",
        "  if repo is not None:\n",
        "    nb2repo(False)\n",
        "    !cd {c['projects_dir']}{repo} && git add -A && echo \"diff from origin:\" && git diff origin --stat && echo -e \"\\033[0m\\n\" && git status\n",
        "\n",
        "def drive_nb2repo_nb(message='update from colab notebooks'):\n",
        "  '''for file in projects_dir/active_project/notebooks/*.ipynb copy Google Drive \n",
        "  \"Colab Notebooks/file.ipynb\" on top of it'''\n",
        "  from google.colab import drive\n",
        "  os.path.isdir('/content/drive/') or drive.mount('/content/drive/')\n",
        "  enbooks = !ls {c['active_project']}/notebooks/*.ipynb\n",
        "  for book in enbooks:\n",
        "    nbfname = os.path.basename(book)\n",
        "    cmd = f\"cp drive/MyDrive/Projects/{c['active_project']}/notebooks/{nbfname} {book}\"\n",
        "    print(cmd)\n",
        "    !{cmd}\n",
        "  git_ppush(message)\n",
        "  # gnbooks = !ls drive/MyDrive/Projects/{c['active_project']}/notebooks/*.ipynb\n",
        "  # print(gnbooks)\n",
        "  # drive/Colab\\ Notebooks/\n",
        "drive_nb2repo_nb()"
      ],
      "metadata": {
        "id": "cnNvIkIP193t",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "1a148e8f-e2b1-4cb1-b000-f8307373cb1c"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "cp drive/MyDrive/Projects/jai/notebooks/bdd_testing_a_notebook.ipynb jai/notebooks/bdd_testing_a_notebook.ipynb\n",
            "cp drive/MyDrive/Projects/jai/notebooks/bootstrap_a_notebook.ipynb jai/notebooks/bootstrap_a_notebook.ipynb\n",
            "cp drive/MyDrive/Projects/jai/notebooks/demo_notebook.ipynb jai/notebooks/demo_notebook.ipynb\n",
            "cp drive/MyDrive/Projects/jai/notebooks/encrypted_config.ipynb jai/notebooks/encrypted_config.ipynb\n",
            "cp: cannot stat 'drive/MyDrive/Projects/jai/notebooks/encrypted_config.ipynb': No such file or directory\n",
            "cp drive/MyDrive/Projects/jai/notebooks/git_for_colab.ipynb jai/notebooks/git_for_colab.ipynb\n",
            "cp drive/MyDrive/Projects/jai/notebooks/notebooks_as_features.ipynb jai/notebooks/notebooks_as_features.ipynb\n",
            "cp drive/MyDrive/Projects/jai/notebooks/vite.ipynb jai/notebooks/vite.ipynb\n",
            "try to write\n",
            "/content/jai/notebooks/git_for_colab.ipynb\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# !cd {c.get('projects_dir')}{c.get('active_project')} && git pull\n",
        "# nb2repo()\n",
        "# git_ppush('remove defunct notebooks')"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "wk9C_oly90mZ",
        "executionInfo": {
          "status": "ok",
          "timestamp": 1673971037713,
          "user_tz": 540,
          "elapsed": 819,
          "user": {
            "displayName": "Jaci ss",
            "userId": "10130648813270993501"
          }
        },
        "outputId": "6259e911-1ecc-4af9-d16d-05315db4a32b"
      },
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "remote: Enumerating objects: 6, done.\u001b[K\n",
            "remote: Counting objects:  16% (1/6)\u001b[K\rremote: Counting objects:  33% (2/6)\u001b[K\rremote: Counting objects:  50% (3/6)\u001b[K\rremote: Counting objects:  66% (4/6)\u001b[K\rremote: Counting objects:  83% (5/6)\u001b[K\rremote: Counting objects: 100% (6/6)\u001b[K\rremote: Counting objects: 100% (6/6), done.\u001b[K\n",
            "remote: Compressing objects:  25% (1/4)\u001b[K\rremote: Compressing objects:  50% (2/4)\u001b[K\rremote: Compressing objects:  75% (3/4)\u001b[K\rremote: Compressing objects: 100% (4/4)\u001b[K\rremote: Compressing objects: 100% (4/4), done.\u001b[K\n",
            "remote: Total 4 (delta 2), reused 0 (delta 0), pack-reused 0\u001b[K\n",
            "Unpacking objects:  25% (1/4)   \rUnpacking objects:  50% (2/4)   \rUnpacking objects:  75% (3/4)   \rUnpacking objects: 100% (4/4)   \rUnpacking objects: 100% (4/4), done.\n",
            "From https://github.com/Jaciss/jai\n",
            "   0851c52..c2b21cb  main       -> origin/main\n",
            "Updating 0851c52..c2b21cb\n",
            "Fast-forward\n",
            " notebooks/encrypted_config.ipynb | 1870 \u001b[32m++++++++++++++++++++++++++++++++++++++\u001b[m\n",
            " 1 file changed, 1870 insertions(+)\n",
            " create mode 100644 notebooks/encrypted_config.ipynb\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# GitHub CLI"
      ],
      "metadata": {
        "id": "ooWLstJ4Ekfs"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "QNXMk3yFcpCY"
      },
      "outputs": [],
      "source": [
        "def get_gh():\n",
        "  '''installs GitHub CLI'''\n",
        "  hazgh = !which gh\n",
        "  if len(hazgh)==0:\n",
        "    command = '''\n",
        "    sudo apt install curl -y\n",
        "    curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \\\n",
        "    && sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \\\n",
        "    && echo \"deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main\" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \\\n",
        "    && sudo apt update \\\n",
        "    && sudo apt install gh -y\n",
        "    '''\n",
        "    !{command} > /dev/null\n",
        "    ghtoken = epc.get_token('github')\n",
        "    !echo \"{ghtoken}\" | gh auth login --with-token"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "def create_private_github_repo(name):\n",
        "  '''creates a private repo, relies on epc'''\n",
        "  get_gh()\n",
        "  user = epc.get_token('github_user')\n",
        "  !gh repo create {name} --private\n",
        "  # private! --clone in above does not work =P\n",
        "  epc.github_fetch({'repo':name,'user':git_user,'token':epc.get_token('github'),'filepath':''})\n",
        "  !cd {name} && echo \"# {name}\" >> README.md \n",
        "  !cd {name} && git add README.md && git commit -m \"initial commit\"\n",
        "  !cd {name} && git branch -M main\n",
        "  !cd {name} && git push -u origin main\n",
        "  !cat {name}/.git/config\n",
        "  !cd {name} && git status\n",
        "# !cd {c['nb_dir']} && git branch --set-upstream-to=origin/dev dev\n",
        "\n",
        "# create_private_github_repo('gotit')"
      ],
      "metadata": {
        "id": "futbro2ZQehU"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "def create_issue(title,body,label='bug',a='@me',idx=0):\n",
        "  '''common labels: bug, enhancement, documentation, question'''\n",
        "  get_gh()\n",
        "  repo = get_repo_name(idx)\n",
        "  response = !cd {repo} && gh issue create -t \"{title}\" -b \"{body}\" -a \"{a}\" -l \"{label}\"\n",
        "  print(' '.join(response))\n",
        "  if len(response)==4: return os.path.basename(response[3])\n",
        "  return response\n",
        "\n",
        "# create_issue('fix knowledge of GitHub closes syntax','this is awesome','enhancement')"
      ],
      "metadata": {
        "id": "xg39NUAVbVGa"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Misc"
      ],
      "metadata": {
        "id": "jz6zJZYiPugd"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# make a copy of active, nbdiff it with what's in the repo dir:\n",
        "# nb2repo(0,'../../tmp/',False)\n",
        "# !cd jai && nbdiff notebooks/git_for_colab.ipynb ../../tmp/git_for_colab.ipynb\n",
        "\n",
        "# to try:\n",
        "# !cd jai && nbdime mergetool\n",
        "\n",
        "# failed to get nbdiff-webweb diff working: https://colab.research.google.com/drive/1frMmd0WSaXhOQXef0PtTWojCXuuvMxur\n",
        "\n",
        "# diff repo with remote\n",
        "# !cd jai && git diff main:notebooks/git_for_colab.ipynb notebooks/git_for_colab.ipynb"
      ],
      "metadata": {
        "id": "SpJHYL43F2N5"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# if you want everything in the root directory:\n",
        "# !mv {repo}/* .\n",
        "# !mv {repo}/.[!.]* .\n",
        "# !rm -rf {repo}"
      ],
      "metadata": {
        "id": "fkiqONrGmd2m"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## diff live vs github files"
      ],
      "metadata": {
        "id": "87lhCrzbC6-D"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# DIFF Live vs Git\n",
        "# # git version\n",
        "# text_file = open(\"jai/notebooks/encrypted_private_config.ipynb\", \"r\")\n",
        "# data = text_file.read()\n",
        "# text_file.close()\n",
        "# jsonFile = open(\"gitnb.json\", \"w\")\n",
        "# jsonFile.write(json.dumps(json.loads(data),indent=2))\n",
        "# jsonFile.close()\n",
        "\n",
        "# # live version\n",
        "# activenb = _message.blocking_request('get_ipynb', request='', timeout_sec=5)['ipynb']\n",
        "# jsonFile = open(\"activenb.json\", \"w\")\n",
        "# jsonFile.write(json.dumps(activenb,indent=2))\n",
        "# jsonFile.close()\n",
        "\n",
        "# # !head gitnb.json\n",
        "# !diff -c activenb.json gitnb.json\n",
        "# !cp activenb.json jai/notebooks/encrypted_private_configTEST.ipynb\n"
      ],
      "metadata": {
        "id": "7tXvcqU2iMY0"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# EOF"
      ],
      "metadata": {
        "id": "wgPmim542Mrz"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# %%writerun {nb_dir}templates/git_message -e\n",
        "#@title Commit Message { run: \"auto\", vertical-output: true }\n",
        "commit_message = \"\" #@param {type:\"string\"}\n",
        "commit_message = c.get('commit_message',commit_message+' |colab')\n",
        "commit_message"
      ],
      "metadata": {
        "id": "r2mlfl-lNwoU",
        "executionInfo": {
          "status": "ok",
          "timestamp": 1673713399092,
          "user_tz": 540,
          "elapsed": 261,
          "user": {
            "displayName": "Jaci ss",
            "userId": "10130648813270993501"
          }
        },
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 36
        },
        "outputId": "40effcd4-afee-4b1b-f56c-cdbbc5eaa4c0"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "' |colab'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 21
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# %%writerun {c['nb_dir']}templates/git -e\n",
        "#@title Git Actions { run: \"auto\", vertical-output: true }\n",
        "if c['running_nb'] == c['nb_name']:\n",
        "  github_index = 0 #@param [\"0\", \"1\", \"2\"] {type:\"raw\"}\n",
        "  git_action = \"nb2repo*\" #@param [\"\",\"nb2repo*\",\"pull\",\"diff\",\"diff origin --minimal\",\"git_nbastatus*\",\"commit -m {message}\",\"push\",\"ppush*\",\"status\",\"fetch\",\"merge\",\"push origin dev\",\"diff main dev\",\"merge main\",\"merge dev\",\"checkout main\",\"checkout dev\",\"diff --staged\",\"restore\",\"add .\",\"branch -a\",\"log -15 --graph --oneline --decorate\",\"reset --hard HEAD\",\"reset --hard HEAD~1\",\"commit --amend -m {messaage}\"]\n",
        "\n",
        "  print('repo indices: '+str(dict(zip(range(len(c['github'])),c['github']))))\n",
        "  if github_index > len(c['github'])-1:\n",
        "    print('no repo at that index')\n",
        "  else:\n",
        "    print('repo:',c['github'][github_index])\n",
        "  if git_action!='':\n",
        "    if git_action=='nb2repo*': nb2repo()\n",
        "    elif git_action=='ppush*': git_ppush(commit_message)\n",
        "    elif git_action=='git_nbastatus*': git_nbastatus(github_index)\n",
        "    else:\n",
        "      if git_action==\"commit -m {message}\": git_action = f\"commit -m '{commit_message}'\"\n",
        "      if git_action==\"commit --amend -m {messaage}\": git_action = f\"commit --amend -m '{commit_message}'\"\n",
        "      !cd {c['github'][github_index]} && git {git_action}"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "xbADLUi2fyfM",
        "executionInfo": {
          "status": "ok",
          "timestamp": 1673713383563,
          "user_tz": 540,
          "elapsed": 1639,
          "user": {
            "displayName": "Jaci ss",
            "userId": "10130648813270993501"
          }
        },
        "outputId": "3fdd3421-8076-40e0-b0c4-4e6b3fcc83ec"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "repo indices: {0: 'jai'}\n",
            "repo: jai\n",
            "-rw-r--r-- 1 root root 25214 Jan 14 07:23 git_for_colab.ipynb\n",
            "\n",
            " notebooks/git_for_colab.ipynb | 2 \u001b[32m+\u001b[m\u001b[31m-\u001b[m\n",
            " 1 file changed, 1 insertion(+), 1 deletion(-)\n",
            "\u001b[0m\n",
            "\n",
            "nbdiff /tmp/jrfDX1_git_for_colab.ipynb notebooks/git_for_colab.ipynb\n",
            "--- /tmp/jrfDX1_git_for_colab.ipynb  2023-01-14 07:23:02.727189\n",
            "+++ notebooks/git_for_colab.ipynb  2023-01-14 07:23:02.580176\n",
            "\u001b[34m## modified /cells/22/source:\u001b[0m\n",
            "\u001b[36m@@ -2,7 +2,7 @@\u001b[m\n",
            " #@title Git Actions { run: \"auto\", vertical-output: true }\u001b[m\n",
            " if c['running_nb'] == c['nb_name']:\u001b[m\n",
            "   github_index = 0 #@param [\"0\", \"1\", \"2\"] {type:\"raw\"}\u001b[m\n",
            "\u001b[31m-  git_action = \"ppush*\" #@param [\"\",\"nb2repo*\",\"pull\",\"diff\",\"diff origin --minimal\",\"git_nbastatus*\",\"commit -m {message}\",\"push\",\"ppush*\",\"status\",\"fetch\",\"merge\",\"push origin dev\",\"diff main dev\",\"merge main\",\"merge dev\",\"checkout main\",\"checkout dev\",\"diff --staged\",\"restore\",\"add .\",\"branch -a\",\"log -15 --graph --oneline --decorate\",\"reset --hard HEAD\",\"reset --hard HEAD~1\",\"commit --amend -m {messaage}\"]\u001b[m\n",
            "\u001b[32m+\u001b[m\u001b[32m  git_action = \"nb2repo*\" #@param [\"\",\"nb2repo*\",\"pull\",\"diff\",\"diff origin --minimal\",\"git_nbastatus*\",\"commit -m {message}\",\"push\",\"ppush*\",\"status\",\"fetch\",\"merge\",\"push origin dev\",\"diff main dev\",\"merge main\",\"merge dev\",\"checkout main\",\"checkout dev\",\"diff --staged\",\"restore\",\"add .\",\"branch -a\",\"log -15 --graph --oneline --decorate\",\"reset --hard HEAD\",\"reset --hard HEAD~1\",\"commit --amend -m {messaage}\"]\u001b[m\n",
            " \u001b[m\n",
            "   print('repo indices: '+str(dict(zip(range(len(c['github'])),c['github']))))\u001b[m\n",
            "   if github_index > len(c['github'])-1:\u001b[m\n",
            "\n",
            "\u001b[0m"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "QP6frE6FX2lK"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# for automatic pushes\n",
        "# if c['nb_run_by'] == c['nb_name']:\n",
        "#   git_ppush('colab')"
      ],
      "metadata": {
        "id": "dUEyAbF4o5sk"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# c['nb_name'] = c['nb_run_by'] # give nb_name back to any calling notebooks"
      ],
      "metadata": {
        "id": "9Ro27GgBF8LZ"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}