main
Kay 2 weeks ago
commit 4567bec5d9
  1. 73
      .README.template.md
  2. 4
      .gitignore
  3. 8
      .gitlab-ci.yml
  4. 25
      CHANGELOG.md
  5. 459
      LICENSE
  6. 131
      README.md
  7. 3
      git-scheduler
  8. 473
      index.mjs
  9. 284
      libs/date_prompt.mjs
  10. 32
      package.json
  11. 15
      webpack.config.js

@ -0,0 +1,73 @@
## install
i am not responsible for any loss of generated value (work) incured
this is an early stage project and things might go wrong only run it if you understand what is going on
### repository
```bash
$ git clone https://code.eutychia.org/kay/git-scheduler.git
$ yarn
```
### npm package
```shell
$ npm_config_registry=https://code.eutychia.org/api/v4/packages/npm npx @kay/git-scheduler@latest
```
you can override `start`, `end` or `rate` specifically per project by creating a `.git-scheduler` file
```json
{
"start": "2022-01-14T08:29:34.626Z",
"end": "2022-01-14T08:29:35.611Z",
"rate": 666
}
```
you do not have to specify every key, you can simply override `rate` only for a given repository if you want for example
## features
- tell it how many of the last commits to schedule (they are converted to patch files and removed from head)
- configure your work hours
- configure the rate at which you want to generate value for capitalistic overlords
## screenshot
**configuration**
the first time you run the tool it will guide you through some setup
if you ever want to access this mode again use the `-c` or `--config` flag
[![a demo of the configuration mode screen](https://i.imgur.com/tIMUVWW.gif)](#)
**patch creation**
this mode allows you to select however many of the latest unpushed commits you want and create patches for them
it is the default mode of the tool, you don't need to pass it any flags
[![a demo of the patch creation mode screen](https://i.imgur.com/8aGBwTh.gif)](#)
**apply**
this mode will simply apply all the currently stored patches for the repository with their original creation dates
you access this mode with the `-a` or `--apply` flag
[![a demo of the apply mode screen](https://i.imgur.com/6SRJboA.gif)](#)
**daemon**
daemon mode is the capitalistic society conformist value generation mode
it will automatically schedule your commits depending on your work preferences :tm:
you access this mode with the `-d` or `--daemon` flag
[![a demo of the daemon mode screen](https://i.imgur.com/f6d2X0p.gif)](#)

4
.gitignore vendored

@ -0,0 +1,4 @@
node_modules
package-lock.json
yarn.lock
dist

@ -0,0 +1,8 @@
---
include:
- project: "kay/ci-templates"
file:
- "/Semantic-Release.gitlab-ci.yml"
stages:
- review

@ -0,0 +1,25 @@
# [1.3.0](https://code.eutychia.org/kay/git-scheduler/compare/v1.2.0...v1.3.0) (2022-06-27)
### Bug Fixes
* Add yarn install ([55693f0](https://code.eutychia.org/kay/git-scheduler/commit/55693f08486489022ce68680fcbdcc20c85f01fa))
### Features
* Add webpacked package deployment ([324c5df](https://code.eutychia.org/kay/git-scheduler/commit/324c5df2d6748fc903fd2899572f04043f524d49))
# [1.2.0](https://code.eutychia.org/kay/git-scheduler/compare/v1.1.0...v1.2.0) (2022-06-26)
### Features
* Update readme ([bcd8535](https://code.eutychia.org/kay/git-scheduler/commit/bcd8535a318b5697b490cab69ab9ecd2e4996b3e))
# [1.1.0](https://code.eutychia.org/kay/git-scheduler/compare/v1.0.0...v1.1.0) (2022-06-26)
### Features
* Update readme ([3f444e6](https://code.eutychia.org/kay/git-scheduler/commit/3f444e6137262bd39218f5be2b318e38b35a383c))

@ -0,0 +1,459 @@
Attribution-NonCommercial-ShareAlike 4.0 International AntiFascistEdit
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International Public License
("Public License"). To the extent this Public License may be
interpreted as a contract, You are granted the Licensed Rights in
consideration of Your acceptance of these terms and conditions, and the
Licensor grants You such rights in consideration of benefits the
Licensor receives from making the Licensed Material available under
these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. BY-NC-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
e. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution, NonCommercial, and ShareAlike.
h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
i. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
k. NonCommercial means not primarily intended for or directed towards
commercial advantage or monetary compensation. For purposes of
this Public License, the exchange of the Licensed Material for
other material subject to Copyright and Similar Rights by digital
file-sharing or similar means is NonCommercial provided there is
no payment of monetary compensation in connection with the
exchange.
l. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
m. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
n. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for
NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. Additional offer from the Licensor -- Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-NC-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
in any reasonable manner based on the medium, means, and
context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database for NonCommercial purposes
only;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
c. The License does not apply and no license is granted for
taking action on behalf of a Nation or State or Government,
be it military, law enforcement, agent, spy, hacker, developer,
this list is not exhaustive.
d. The License does not apply and no license is granted to actors
taking action to oppress, harm, injure, kill, whether
physically or psycholocially.
e. The License does not apply and no license is granted to actors
acting on behalf of any party previously found guilty of committing
war crimes at any point in time.
f. The License does not apply and no license is granted to actors
acting on behalf of any party previously found not respecting the
Universal Declaration of Human Rights at any point in time.
g. The License does not apply and no license is granted to actors
acting with the intent of surveilling a population or the intent of
gathering information on spefific or non-specific populations and/or
target demographics.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.

@ -0,0 +1,131 @@
# [git-scheduler](https://code.juke.fr/kay/git-scheduler)
schedule git commits to pass as "normal" timezone person
## install
i am not responsible for any loss of generated value (work) incured
this is an early stage project and things might go wrong only run it if you understand what is going on
### repository
```bash
$ git clone https://code.eutychia.org/kay/git-scheduler.git
$ yarn
```
### npm package
```shell
$ npm_config_registry=https://code.eutychia.org/api/v4/packages/npm npx @kay/git-scheduler@latest
```
you can override `start`, `end` or `rate` specifically per project by creating a `.git-scheduler` file
```json
{
"start": "2022-01-14T08:29:34.626Z",
"end": "2022-01-14T08:29:35.611Z",
"rate": 666
}
```
you do not have to specify every key, you can simply override `rate` only for a given repository if you want for example
## features
- tell it how many of the last commits to schedule (they are converted to patch files and removed from head)
- configure your work hours
- configure the rate at which you want to generate value for capitalistic overlords
## screenshot
**configuration**
the first time you run the tool it will guide you through some setup
if you ever want to access this mode again use the `-c` or `--config` flag
[![a demo of the configuration mode screen](https://i.imgur.com/tIMUVWW.gif)](#)
**patch creation**
this mode allows you to select however many of the latest unpushed commits you want and create patches for them
it is the default mode of the tool, you don't need to pass it any flags
[![a demo of the patch creation mode screen](https://i.imgur.com/8aGBwTh.gif)](#)
**apply**
this mode will simply apply all the currently stored patches for the repository with their original creation dates
you access this mode with the `-a` or `--apply` flag
[![a demo of the apply mode screen](https://i.imgur.com/6SRJboA.gif)](#)
**daemon**
daemon mode is the capitalistic society conformist value generation mode
it will automatically schedule your commits depending on your work preferences :tm:
you access this mode with the `-d` or `--daemon` flag
[![a demo of the daemon mode screen](https://i.imgur.com/f6d2X0p.gif)](#)
## License
Most all of my work is now licensed under **a modified** [CC-BY-NC-SA 4.0 AFEdit](https://code.juke.fr/kay/license/raw/branch/main/LICENSE) plus accounting for states existing in our world on top of capitalism.
This is a weird choice for code right?
Here are a few key reasons:
- my definition of "open" involves being able to share and modify, you are able to do such things, just not make money off of it, or oppress people
- my definition of "free" involves being able to share and modify, you are able to do such things, not just make money off of it, or oppressing people
So no, amongst other things, this list is not exhaustive,
- you cannot have somebody work on my tool and redistribute it to your employees
- you cannot resell copies of this because in this age distribution is not done with floppy disks and the internet is a thing
- you cannot use it to generate revenue yourself
- you cannot use it to "generate value" in a capitalistic sense
- you cannot use it in any military capacity
- you cannot use it in any law enforcement capacity
- you cannot use it in any state backed capacity
- you cannot use it in any surveillance capacity
- you cannot use it if you represent the interests of a state
- you cannot use it to oppress, spy, control in any capacity
- you cannot use it to injure, harm, kill, whether physically or psychologically
You can, however,
- change it to do whatever you please
- share it to anyone you please with attribution and under the same license
- use it as much as you please
- and probably a bunch of other cool things that are possible outside of a capitalistic, imperialistic frame of reference that permeates the tech scene
Most of the "arguments" for how "free" and "open" source licenses are done still to this day stem from archaic concepts that might not even be relevant these days and I fail to see the issue with this license not being "interoperable" with a bunch of what I deem to be "bad" licenses, as they all allow for commercial usage.
I also will not make any attempts to monetize these works and will at most ever offer the possibility to donate to me directly if you enjoy what I do.
Thank you that is all.
## Development
To clone the repository locally:
```bash
$ git clone https://code.juke.fr/kay/git-scheduler.git
```
## Contributing
More to come later.
### Issues
Open new issues by mailing [eutychia.gitlab+git-scheduler-issue@gmail.com](mailto:eutychia.gitlab+git-scheduler-issue@gmail.com)
---
beep boop

@ -0,0 +1,3 @@
#!/usr/bin/env node
require("./dist/bundle");

@ -0,0 +1,473 @@
import chalk from "chalk";
import inquirer from "inquirer";
import { DatePrompt } from "./libs/date_prompt.mjs";
import Conf from "conf";
import { program } from "commander";
import { homedir, EOL } from "os";
import {
existsSync,
readFileSync,
appendFileSync,
writeFileSync,
readdirSync,
unlinkSync,
} from "fs";
import { join, sep, dirname } from "path";
import moment from "moment";
import { cwd } from "process";
import { promisify } from "util";
import { exec } from "child_process";
const execp = promisify(exec);
inquirer.registerPrompt("date", DatePrompt);
program.version(process.env.npm_package_version);
program
.option("-c, --configure", "run configuration mode")
.option("-d, --daemon", "run commit mode")
.option("-a, --apply", "run apply all pending patches mode");
program.parse(process.argv);
const program_options = program.opts();
const config = new Conf();
const home = homedir();
// this is so fucking cursed lmaooo
const processDirectory = cwd();
const pathSplit = (path) =>
path
.split(sep)
.map((dir, currentIndex, arr) => {
let result = "";
for (let index = 0; index <= currentIndex; index++) {
// could probably be recursed but brain melty rn
result = join(result, arr[index]);
}
return result;
})
.splice(1) // first value will always be drive root we dont care about it (probably ?)
.map((v) => `${sep}${v}`); // dont even worry about it
const detectGitRepository = (paths) =>
paths.reduce(
(previous, current, index) => {
if (previous.found) {
return previous;
}
const exists = existsSync(join(current, ".git"));
return { index, found: exists };
},
{ index: -1, found: false },
);
(async () => {
console.log(`welcome to ${chalk.bold.red("git-scheduler")}${EOL}`);
// TODO: make this smarter
if (
(program_options.daemon && program_options.apply) ||
(program_options.daemon && program_options.configure) ||
(program_options.configure && program_options.apply) ||
(program_options.daemon &&
program_options.apply &&
program_options.configure)
) {
console.log(
`only one mode can be active at ${chalk.bold.red("the same time")}`,
);
process.exit(1);
}
// TODO: add a push config option and cli toggle
// configuration
const already_ran_once = config.get("already_ran_once");
if (!already_ran_once || program_options.configure) {
console.log(
`it seems that this is ${chalk.red(
"your first",
)} time running this utility${EOL}`,
);
// gitignore
console.log(
`git-scheduler handles ${chalk.red(
".git-scheduler",
)} files to configure repositories individually`,
);
console.log(
`it is ${chalk.red(
"highly recommended",
)} that you add this file to your global .gitignore to not commit and push it`,
);
const { first_run_gitignore } = await inquirer.prompt([
{
type: "confirm",
name: "first_run_gitignore",
message: `would you like to add the ${chalk.bold.red(
".git-scheduler",
)} config file to your global ${chalk.bold.red(".gitignore")} ?`,
},
]);
const gitignoreTemplate = `${EOL}#########################################${EOL}# automatically appended by git-scheduler${EOL}.git-scheduler${EOL}#########################################${EOL}`;
if (first_run_gitignore) {
const globalGitignore = join(home, ".gitignore");
if (existsSync(globalGitignore)) {
const content = readFileSync(globalGitignore, "utf-8");
const contentArray = content.split(EOL);
const found = contentArray.indexOf(".git-scheduler");
if (found !== -1) {
console.log(".git-scheduler already ignored, skipping");
} else {
console.log("appending .git-scheduler to global .gitignore file");
const result = appendFileSync(globalGitignore, gitignoreTemplate);
}
} else {
console.log("could not find global .gitignore file, creating it");
const result = writeFileSync(globalGitignore, gitignoreTemplate);
}
}
// work hours
let shouldAskForWorkHours = true;
if (
config.get("first_run_work_hours_start") &&
config.get("first_run_work_hours_start")
) {
console.log(
`${EOL}you already have some work hours setup, starting at ${chalk.red(
moment(config.get("first_run_work_hours_start")).format("hh:mm A"),
)}, and ending at ${chalk.red(
moment(config.get("first_run_work_hours_end")).format("hh:mm A"),
)}`,
);
const { reset_hours } = await inquirer.prompt([
{
type: "confirm",
name: "reset_hours",
message: `would you like to reconfigure the ${chalk.bold.red(
"work hours",
)} ?`,
default: false,
},
]);
shouldAskForWorkHours = reset_hours;
}
if (shouldAskForWorkHours) {
console.log(
`${EOL}now lets setup your ${chalk.red(
"work hours",
)} to know when the commits should be made`,
);
console.log(
`you can use your ${chalk.red("arrow keys")} to set the times`,
);
const { first_run_work_hours_start, first_run_work_hours_end } =
await inquirer.prompt([
{
type: "date",
name: "first_run_work_hours_start",
message: `at what time does your work ${chalk.bold.red("start")} ?`,
format: { month: undefined, year: undefined, day: undefined },
},
{
type: "date",
name: "first_run_work_hours_end",
message: `at what time does your work ${chalk.bold.red("end")} ?`,
format: { month: undefined, year: undefined, day: undefined },
},
]);
config.set("first_run_work_hours_start", first_run_work_hours_start);
config.set("first_run_work_hours_end", first_run_work_hours_end);
}
console.log("work hours configured");
// value generation rate
// TODO: for now we ask how many lines we want to push in a day but thats probably not the best idea
console.log(
`${EOL}we will now configure the ${chalk.red(
"rate",
)} at which the commits should be made`,
);
console.log(
`this takes into account the ${chalk.red(
"size",
)} of each individual commit`,
);
const { first_run_generation_rate } = await inquirer.prompt([
{
type: "number",
name: "first_run_generation_rate",
message: `how fast should we be ${chalk.bold.red(
"generating value",
)} (lines of code per day) ?`,
default: config.get("first_run_generation_rate") || 100,
},
]);
config.set("first_run_generation_rate", first_run_generation_rate);
console.log("generation rate configured");
config.set("already_ran_once", true);
if (program_options.configure) process.exit(0);
}
// main logic
// check if current directory is git repo
const paths = pathSplit(processDirectory);
const detected = detectGitRepository(paths);
if (detected.found) {
const path = paths[detected.index];
console.log(`detected git repository ${chalk.bold.red(path)}`);
const { detected_git_repo } = await inquirer.prompt([
{
type: "confirm",
name: "detected_git_repo",
message: `is this ${chalk.bold.red("correct")} ?`,
},
]);
if (!detected_git_repo) {
console.log("aborting");
process.exit(1);
}
// check if it contains a gitscheduler file and parse it as options
const possibleConfigOverridePath = join(path, ".git-scheduler");
const hasGitSchedulerConfig = existsSync(possibleConfigOverridePath);
let options = {
start: config.get("first_run_work_hours_start"),
end: config.get("first_run_work_hours_end"),
rate: config.get("first_run_generation_rate"),
};
if (hasGitSchedulerConfig) {
console.log(
`${EOL}.git-scheduler configuration file ${chalk.bold.red("detected")}`,
);
const configContents = JSON.parse(
readFileSync(possibleConfigOverridePath, "utf-8"),
);
options = { ...options, ...configContents };
console.log(
`repository specific configuration ${chalk.bold.red(
"overrides",
)} applied`,
);
} else {
console.log(
`${EOL}.git-scheduler configuration file ${chalk.bold.red(
"not present",
)}, using defaults`,
);
}
console.log();
// console.log(`current ${chalk.bold.red("configuration")} is`);
// console.log(`${JSON.stringify(options, 0, 2)}${EOL}`);
async function waitUntil(time) {
return await new Promise((resolve) => {
const interval = setInterval(() => {
if (moment().isAfter(moment(time))) {
resolve("foo");
clearInterval(interval);
}
}, 1000);
});
}
// daemon mode
if (program_options.daemon) {
const configDir = dirname(config.path);
const uid = config.get(path);
if (!uid) {
console.log(
`current repository ${chalk.bold.red("not found")} in configuration`,
);
console.log(
`assuming ${chalk.bold.red(
"no patches",
)} to apply or a ${chalk.bold.red("corrupt")} configuration`,
);
console.log(
`see ${chalk.bold.red(
configDir,
)} directly if this is not supposed to happen`,
);
process.exit(1);
}
const files = readdirSync(configDir);
const patches = files
.filter((file) => file.includes(`patch_${uid}`))
.sort()
.map((patchFile) => join(configDir, patchFile));
if (patches.length === 0) {
console.log("no patches to apply");
process.exit(1);
}
for (const patch of patches) {
const patchContent = readFileSync(patch, "utf-8");
const lines = patchContent.split(EOL);
// TODO: improve magic math part
const ratio = lines.length / options.rate;
console.log(
`this patch represents ${chalk.bold.red(
Math.round(ratio * 100),
)}% of daily code rate`,
);
// TODO: add a value to config to say how much time was left over at end of day and add it to start of next day maths
const workingTime = moment(options.end).diff(moment(options.start));
const duration = moment
.utc(moment.duration(workingTime).as("milliseconds"))
.format("HH:mm");
console.log(`you work ${chalk.bold.red(duration)} hours in a day`);
const proportionalValueGeneration = ratio * workingTime;
const proportionalDuration = moment
.utc(moment.duration(proportionalValueGeneration).as("milliseconds"))
.format("HH:mm:ss");
console.log(
`we will be spending ${chalk.bold.red(
proportionalDuration,
)} hours on this patch`,
);
const waitDate = moment().add(proportionalValueGeneration);
await waitUntil(waitDate);
console.log("i have worked very well, applying patch");
lines[2] = `Date: ${moment().format("ddd, D MMM YYYY HH:mm:ss ZZ")}`;
writeFileSync(`${patch}`, lines.join(EOL));
await execp(`git -C ${path} am < ${patch}`);
unlinkSync(patch);
console.log("pushing");
await execp(`git -C ${path} push`);
}
// TODO: handle day start and end times
console.log("all done with the patches");
process.exit(0);
}
// apply mode
if (program_options.apply) {
const configDir = dirname(config.path);
const uid = config.get(path);
if (!uid) {
console.log(
`current repository ${chalk.bold.red("not found")} in configuration`,
);
console.log(
`assuming ${chalk.bold.red(
"no patches",
)} to apply or a ${chalk.bold.red("corrupt")} configuration`,
);
console.log(
`see ${chalk.bold.red(
configDir,
)} directly if this is not supposed to happen`,
);
process.exit(1);
}
const files = readdirSync(configDir);
const patches = files
.filter((file) => file.includes(`patch_${uid}`))
.sort()
.map((patchFile) => join(configDir, patchFile));
if (patches.length === 0) {
console.log("no patches to apply");
process.exit(1);
}
for (const patch of patches) {
await execp(`git -C ${path} am < ${patch}`);
unlinkSync(patch);
}
console.log(
`${EOL}done applying ${chalk.bold.red(patches.length)} patches`,
);
process.exit(0);
}
// patch creation mode
const branch = await execp(`git -C ${path} rev-parse --abbrev-ref HEAD`);
const log = await execp(
`git -C ${path} log --oneline origin/${branch.stdout.trim()}..HEAD`,
);
const choices = log.stdout
.trim()
.split(EOL)
.filter((v) => v)
.map((v, i) => `${i + 1}) ${v}`);
let howManyCommits = 0;
if (choices.length > 0) {
const { how_far_back } = await inquirer.prompt([
{
type: "list",
name: "how_far_back",
message: `how many unpushed commits back do we want to ${chalk.bold.red(
"schedule",
)} ?`,
default: 0,
choices,
},
]);
howManyCommits = choices.indexOf(how_far_back) + 1;
} else {
console.log(`${EOL}no unpushed commits ${chalk.bold.red("detected")}`);
}
let uid = config.get(path);
if (howManyCommits > 0) {
let patches = [];
for (let index = 0; index < howManyCommits; index++) {
patches.push(
(
await execp(
`git -C ${path} format-patch -1 --keep-subject --stdout HEAD`,
)
).stdout,
); // add patch to array
await execp(`git -C ${path} reset --hard HEAD~1`); // hard remove this commit from head
}
patches = patches.reverse();
for (let index = 0; index < howManyCommits; index++) {
uid = Buffer.from(path).toString("base64");
config.set(path, uid);
// TODO: check if some patches are already there and resume indexing from there ?
writeFileSync(
join(dirname(config.path), `patch_${uid}_${index}.patch`),
patches[index],
);
}
console.log(
`${EOL}done creating ${chalk.bold.red(
howManyCommits,
)} patches and removing commits from head`,
);
console.log(
`you may now run the tool in ${chalk.bold.red(
"daemon",
)} or ${chalk.bold.red("apply")} mode`,
);
}
} else {
console.log(`git repository ${chalk.bold.red("not found")}`);
}
})();

@ -0,0 +1,284 @@
// YOINKED FROM
// https://github.com/haversnail/inquirer-date-prompt
// AND TURNED INTO ECMASCRIPT COMPATIBLE MODULE
// (its mit anyways sue me lmao)
import chalk from "chalk";
import cliCursor from "cli-cursor";
import Prompt from "inquirer/lib/prompts/base.js";
import observe from "inquirer/lib/utils/events.js";
// const Prompt = require("inquirer/lib/prompts/base");
// const observe = require("inquirer/lib/utils/events");
import { map, takeUntil } from "rxjs/operators";
/**
* A lookup object that maps each date part type to the corresponding
* getter & setter method on the `Date` prototype.
* @type {Record<Intl.DateTimeFormatPartTypes, keyof Date>}
*/
const fnLookup = {
year: "FullYear",
month: "Month",
day: "Date",
hour: "Hours",
minute: "Minutes",
second: "Seconds",
};
/**
* @type {Intl.DateTimeFormatPartTypes[]}
*/
const editableTypes = Object.keys(fnLookup);
/**
* Returns the index of the _last_ element in the array where predicate is true, and -1 otherwise.
* @template {*} T
* @param {T[]} array
* @param {(value: T, index: number, obj: T[]) => boolean} predicate
*/
const findLastIndex = function findLastIndex(array, predicate) {
let l = array.length;
while (l--) {
if (predicate(array[l], l, array)) return l;
}
return -1;
};
/**
* Represents a date prompt.
*/
class DatePrompt extends Prompt {
constructor(questions, rl, answers) {
super(questions, rl, answers);
// If default value is not a date, throw an error:
if (this.opt.default && !(this.opt.default instanceof Date)) {
throw new Error("The `default` parameter should be a date instance");
}
// Set the format object based on the user's specified options:
const { locale, format = {} } = this.opt;
this.format = Intl.DateTimeFormat(locale, {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
...format,
});
// Set the date object with either the default value or the current date:
this.date = this.opt.default || new Date();
// Clear the default value option (so it won't be printed by the Prompt class):
this.opt.default = null;
// Set the initial dirty state:
this.isDirty = false;
// Set the initial cleared state:
this.isCleared = false;
// Set the first and last indices of the editable date parts:
this.firstEditableIndex = this.dateParts.findIndex((part) =>
editableTypes.includes(part.type),
);
this.lastEditableIndex = findLastIndex(this.dateParts, (part) =>
editableTypes.includes(part.type),
);
// Set the cursor index to the first editable part:
this.cursorIndex = this.firstEditableIndex;
}
// Called by parent class:
_run(cb) {
this.done = cb;
// Observe events:
const events = observe(this.rl);
const submit = events.line.pipe(
map(() => (this.isCleared ? null : this.date)),
);
const validation = this.handleSubmitEvents(submit);
validation.success.forEach(this.onEnd.bind(this));
validation.error.forEach(this.onError.bind(this));
events.keypress
.pipe(takeUntil(validation.success))
.forEach(this.onKeypress.bind(this));
// Init the prompt:
cliCursor.hide();
this.render();
return this;
}
/**
* Renders the prompt.
* @param {string} [error]
*/
render(error) {
let message = this.getQuestion(); // The question portion of the output, including any prefix and suffix
const { isDirty, isCleared } = this;
const isFinal = this.status === "answered";
if (!isCleared) {
const dateString = this.dateParts
.map(({ value }, index) =>
isFinal
? chalk.cyan(value)
: index === this.cursorIndex
? chalk.inverse(value)
: !isDirty
? chalk.dim(value)
: value,
)
.join("");
// Apply the transformer function if one was provided:
message += this.opt.transformer
? this.opt.transformer(dateString, this.answers, {
isDirty,
isCleared,
isFinal,
})
: dateString;
// Display info on how to clear if the prompt is clearable:
if (this.opt.clearable && !isFinal) {
message += chalk.dim(" (<delete> to clear) ");
}
}
const bottomContent = error ? chalk.red(">> ") + error : "";
// Render the final message:
this.screen.render(message, bottomContent);
}
/**
* The end event handler.
* @param {import('inquirer').prompts.SuccessfulPromptStateData<Date | null>} state
*/
onEnd({ value }) {
this.answer = value;
this.status = "answered";
// Re-render prompt
this.render();
this.screen.done();
cliCursor.show();
this.done(value);
}
/**
* The error event handler.
* @param {import('inquirer').prompts.FailedPromptStateData} state
*/
onError({ isValid }) {
this.render(isValid);
}
/**
* The array of date part objects according to the user's specified format.
*/
get dateParts() {
return this.format.formatToParts(this.date);
}
/**
* The currently selected date part.
*/
get currentDatePart() {
return this.dateParts[this.cursorIndex];
}
/**
* A Boolean value indicating whether the currently selected date part is editable.
*/
get isCurrentDatePartEditable() {
return !editableTypes.includes(this.currentDatePart.type);
}
/**
* Moves the cursor index to the right.
*/
incrementCursorIndex() {
if (this.cursorIndex < this.lastEditableIndex) {
this.cursorIndex++;
}
}
/**
* Moves the cursor index to the left.
*/
decrementCursorIndex() {
if (this.cursorIndex > this.firstEditableIndex) {
this.cursorIndex--;
}
}
/**
* Shifts the currently selected date part to the specified offset value.
* The default value is `0`.
* @param {number} offset
*/
shiftDatePartValue(offset = 0) {
// Set the input as "dirty" now that the initial date is being changed:
this.isDirty = true;
const { type } = this.currentDatePart;
if (fnLookup[type]) {
const setter = "set" + fnLookup[type];
const getter = "get" + fnLookup[type];
this.date[setter](this.date[getter]() + offset);
}
}
/**
* Increments the currently selected date part by one.
*/
incrementDatePartValueBy(value = 1) {
this.shiftDatePartValue(value);
}
/**
* Decrements the currently selected date part by one.
*/
decrementDatePartValueBy(value = 1) {
this.shiftDatePartValue(-1 * value);
}
/**
* The keypress event handler.
* @typedef {{ key: import('readline').Key, value?: string }} KeyDescriptor
* @param {KeyDescriptor} descriptor
*/
onKeypress({ key }) {
// Reset cleared state if any other key is pressed:
if (this.isCleared) this.isCleared = false;
// Calculate the amount to increment/decrement by based on modifiers:
const amount = key.shift ? (key.meta ? 100 : 10) : 1;
switch (key.name) {
case "right":
do {
this.incrementCursorIndex();
} while (this.isCurrentDatePartEditable); // increments the cursor index until it hits an editable value
break;
case "left":
do {
this.decrementCursorIndex();
} while (this.isCurrentDatePartEditable); // decrements the cursor index until it hits an editable value
break;
case "up":
this.incrementDatePartValueBy(amount);
break;
case "down":
this.decrementDatePartValueBy(amount);
break;
case "delete":
case "backspace":
if (this.opt.clearable) this.isCleared = true;
break;
}
this.render();
}
}
export { DatePrompt };

@ -0,0 +1,32 @@
{
"name": "@kay/git-scheduler",
"version": "1.3.0",
"description": "schedule your work, because fuck you",
"bin": "./git-scheduler",
"files": [
"git-scheduler",
"dist"
],
"scripts": {
"build": "yarn && webpack",
"start": "node dist/bundle.js"
},
"repository": {
"type": "git",
"url": "git@code.eutychia.org:kay/git-scheduler.git"
},
"keywords": [],
"author": "",
"license": "SEE LICENSE IN LICENSE.CNPLv7+.md",
"devDependencies": {
"chalk": "^5.0.0",
"cli-cursor": "^4.0.0",
"commander": "^8.3.0",
"conf": "^10.1.1",
"inquirer": "^8.2.0",
"moment": "^2.29.1",
"rxjs": "^7.5.2",
"webpack": "^5.73.0",
"webpack-cli": "^4.10.0"
}
}

@ -0,0 +1,15 @@
const path = require("path");
module.exports = {