ncn 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d459f6e9c00f76ef3d4f6ddbdb6cab64ff1d394480d189c930fc700de7f8d4ac
4
+ data.tar.gz: 16f4cc234e4a34f668c5a6ce838b5b0c349167bf2ef89a04f193d854a55cc47b
5
+ SHA512:
6
+ metadata.gz: 2d3595eb1d430954e94701c7d63bf1eb0756beef70d6bc40e9bdb2198a2ad14b89264443af4c97e7bc4638aba60a5c2806df73388de1070fc5d1aa1cfe58c904
7
+ data.tar.gz: d7e4052e202af9e5fb1884c443518f07ca4f763e572a8c8a3bbdf5630f7c254b2234ebebc7db67d3c7ef59098efd2d7cdc376f77cd2fa99517ded8c3b1d492f5
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,4 @@
1
+ require: standard
2
+
3
+ inherit_gem:
4
+ standard: config/base.yml
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-04-06
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at alex.musayev@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,73 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ ncn (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ amazing_print (1.4.0)
10
+ ast (2.4.2)
11
+ byebug (11.1.3)
12
+ coderay (1.1.3)
13
+ diff-lcs (1.5.0)
14
+ method_source (1.0.0)
15
+ parallel (1.22.1)
16
+ parser (3.1.1.0)
17
+ ast (~> 2.4.1)
18
+ pry (0.14.1)
19
+ coderay (~> 1.1)
20
+ method_source (~> 1.0)
21
+ pry-byebug (3.8.0)
22
+ byebug (~> 11.0)
23
+ pry (~> 0.10)
24
+ rainbow (3.1.1)
25
+ rake (13.0.6)
26
+ regexp_parser (2.2.1)
27
+ rexml (3.2.5)
28
+ rspec (3.11.0)
29
+ rspec-core (~> 3.11.0)
30
+ rspec-expectations (~> 3.11.0)
31
+ rspec-mocks (~> 3.11.0)
32
+ rspec-core (3.11.0)
33
+ rspec-support (~> 3.11.0)
34
+ rspec-expectations (3.11.0)
35
+ diff-lcs (>= 1.2.0, < 2.0)
36
+ rspec-support (~> 3.11.0)
37
+ rspec-mocks (3.11.0)
38
+ diff-lcs (>= 1.2.0, < 2.0)
39
+ rspec-support (~> 3.11.0)
40
+ rspec-support (3.11.0)
41
+ rubocop (1.26.0)
42
+ parallel (~> 1.10)
43
+ parser (>= 3.1.0.0)
44
+ rainbow (>= 2.2.2, < 4.0)
45
+ regexp_parser (>= 1.8, < 3.0)
46
+ rexml
47
+ rubocop-ast (>= 1.16.0, < 2.0)
48
+ ruby-progressbar (~> 1.7)
49
+ unicode-display_width (>= 1.4.0, < 3.0)
50
+ rubocop-ast (1.16.0)
51
+ parser (>= 3.1.1.0)
52
+ rubocop-performance (1.13.3)
53
+ rubocop (>= 1.7.0, < 2.0)
54
+ rubocop-ast (>= 0.4.0)
55
+ ruby-progressbar (1.11.0)
56
+ standard (1.9.0)
57
+ rubocop (= 1.26.0)
58
+ rubocop-performance (= 1.13.3)
59
+ timecop (0.9.5)
60
+ unicode-display_width (2.1.0)
61
+
62
+ PLATFORMS
63
+ arm64-darwin-21
64
+
65
+ DEPENDENCIES
66
+ amazing_print (~> 1.4)
67
+ ncn!
68
+ pry
69
+ pry-byebug
70
+ rake (~> 13.0)
71
+ rspec (~> 3.11)
72
+ standard (~> 1.8)
73
+ timecop (~> 0.9.5)
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Alex Musayev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # Taking notes, UNIX way
2
+
3
+ CLI tool for personal notes management. Inspired by [other](https://getdnote.com) [similar](https://github.com/xwmx/nb) [projects](https://jrnl.sh), but subjectively more convenient out of the box.
4
+
5
+ Written in Ruby with <3 and zero dependencies.
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ require "standard/rake"
7
+
8
+ task default: %i[spec standard]
data/bin/console ADDED
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "ncn"
5
+
6
+ Bundler.require
7
+
8
+ lib_path = File.expand_path(File.join("..", "lib"), __dir__)
9
+ $LOAD_PATH << lib_path if File.exist?(lib_path)
10
+
11
+ require "pry"
12
+
13
+ Pry.start
data/bin/ncn ADDED
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "ncn"
5
+
6
+ DEBUG = ENV.key?("NOTES_DEBUG")
7
+
8
+ require "pry" if DEBUG
9
+
10
+ lib_path = File.expand_path(File.join("..", "lib"), __dir__)
11
+ $LOAD_PATH << lib_path if File.exist?(lib_path)
12
+
13
+ Ncn::Main.new.run
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,20 @@
1
+ # Create
2
+
3
+ Generate a blank note and open it with the `$EDITOR`.
4
+
5
+ Usage:
6
+
7
+ ```
8
+ ncn create
9
+ ```
10
+
11
+ Short form:
12
+
13
+ ```
14
+ ncn
15
+ ```
16
+
17
+ Options:
18
+
19
+ - `--path` (optional) — local path to the notes repository. The directory will be created if not present. Default repository path is `$PWD`.
20
+ - `--tags` (optional) — add any number of tags to the new note. Use comma to separate multiple values.
@@ -0,0 +1,19 @@
1
+ # Open
2
+
3
+ Open an existing note with the `$EDITOR`.
4
+
5
+ Usage:
6
+
7
+ ```
8
+ ncn open ID
9
+ ```
10
+
11
+ When `ID` argument is omitted, it will open the most recent note, or do nothing if the repository is empty.
12
+
13
+ ```
14
+ ncn open
15
+ ```
16
+
17
+ Options:
18
+
19
+ - `--path` (optional) — local path to the notes repository. Default repository path is `$PWD`.
data/docs/structure.md ADDED
@@ -0,0 +1,46 @@
1
+ # Structure
2
+
3
+ This document describes basic `ncn` concepts and data formats.
4
+
5
+ ## Notes repository
6
+
7
+ Repository is an ordinary directory in a file system, containing note files and service data, like cache.
8
+
9
+ Repository structure suppose to be managed automatically, though the logic is very generic, allowing multiple usage scenarios.
10
+
11
+ ## Directory structure
12
+
13
+ Note file name and path suppose to be managed automatically, but the structure is quite straightforward:
14
+
15
+ ```
16
+ ROOT/YYYY/MM/DD/ID.ext
17
+ ```
18
+
19
+ - `ROOT` — root notes repository directory.
20
+ - `YYYY/MM/DD` — note creation date.
21
+ - `ID` — unique note ID (an integer serial number).
22
+ - `ext` (optional) — note file extension, default is `md`.
23
+ - File that does not match this structure are considered non-valid notes and will be ignored during lookups.
24
+
25
+ ## Note
26
+
27
+ Each note is a plain text file with optional [YAML front matter](https://jekyllrb.com/docs/front-matter/):
28
+
29
+ ```
30
+ ---
31
+ title: Arbitrary note title
32
+ tags: comma, separated, tags, spaces are ok
33
+ ---
34
+
35
+ Hello world, I'm a note!
36
+ ```
37
+
38
+ ## Note id
39
+
40
+ Each note has a unique id, a serial number for a file within the repository.
41
+
42
+ Id is the primary way to reference a note.
43
+
44
+ Each new id is based on the current repository state.
45
+
46
+ Ids are considered immutable.
data/lib/ncn/cache.rb ADDED
@@ -0,0 +1,53 @@
1
+ module Ncn
2
+ class Cache
3
+ attr_reader :path
4
+
5
+ def initialize(path)
6
+ @path = path
7
+ end
8
+
9
+ def fetch(key, value = nil)
10
+ return get(key) if exist?(key)
11
+ (value || (block_given? ? yield : nil))&.tap { set(key, _1) }
12
+ end
13
+
14
+ def exist?(key)
15
+ cache.key?(key.to_s)
16
+ end
17
+
18
+ # Add key with associated value to the cache
19
+ # @param [String] cache key
20
+ # @param [String] value to associate with the key
21
+ # @return [Object] original value
22
+ def set(key, value)
23
+ cache[key.to_s] = value
24
+ persist
25
+ value
26
+ end
27
+
28
+ def get(key)
29
+ cache[key.to_s]
30
+ end
31
+
32
+ def unset(key)
33
+ return unless exist?(key)
34
+ cache.delete(key.to_s)
35
+ persist
36
+ end
37
+
38
+ def keys
39
+ cache.keys
40
+ end
41
+
42
+ private
43
+
44
+ def persist
45
+ FileUtils.mkdir_p(File.dirname(path))
46
+ File.write(path, JSON.generate(cache))
47
+ end
48
+
49
+ def cache
50
+ @cache ||= File.exist?(path) ? JSON.parse(File.read(path)) : {}
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,29 @@
1
+ module Ncn
2
+ class CliParser
3
+ attr_reader :options, :command, :arguments
4
+
5
+ COMMON_OPTIONS = [
6
+ ["--help", "-h", GetoptLong::NO_ARGUMENT],
7
+ ["--tags", "-t", GetoptLong::REQUIRED_ARGUMENT],
8
+ ["--path", GetoptLong::REQUIRED_ARGUMENT],
9
+ ["--number", "-n", GetoptLong::REQUIRED_ARGUMENT]
10
+ ].freeze
11
+
12
+ NORMALIZERS = {
13
+ "--tags" => ->(value) { value.to_s.split(",").map(&:strip).uniq(&:downcase) },
14
+ "--number" => ->(value) { value.match?(/^\d+$/) ? Integer(value) : nil }
15
+ }.freeze
16
+
17
+ def initialize
18
+ options_parser = GetoptLong.new(*COMMON_OPTIONS)
19
+
20
+ @options = {}.tap do |result|
21
+ options_parser.each do |option, argument|
22
+ result[option] = NORMALIZERS.key?(option) ? NORMALIZERS[option].call(argument) : argument
23
+ end
24
+ end
25
+
26
+ @command, *@arguments = ARGV
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,18 @@
1
+ module Ncn
2
+ module Command
3
+ class Base
4
+ attr_reader :repository, :params
5
+
6
+ # @param repository [Repository]
7
+ # @param params [CommandParams]
8
+ def initialize(repository:, params: nil)
9
+ @repository = repository
10
+ @params = params
11
+ end
12
+
13
+ def perform
14
+ raise "not implemented"
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,10 @@
1
+ module Ncn
2
+ module Command
3
+ class Create < Base
4
+ def perform
5
+ note = repository.create(tags: params.tags)
6
+ Draft.new(ids: [note.id], repository: repository).open_with(&Editor)
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,22 @@
1
+ module Ncn
2
+ module Command
3
+ class Help < Base
4
+ HELP = <<~TEXT
5
+ Usage:
6
+
7
+ create - generate new note and open it with the $EDITOR
8
+ open - open one or multiple notes as a single draft
9
+ help - list all commands or display detailed help for a specific command
10
+
11
+ Common options:
12
+
13
+ --help - similar to the help command
14
+ --path - repository directory path (default is "notes" in the current directory)
15
+ TEXT
16
+
17
+ def perform
18
+ puts HELP
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,9 @@
1
+ module Ncn
2
+ module Command
3
+ class List < Base
4
+ def perform
5
+ puts repository.list
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,15 @@
1
+ module Ncn
2
+ module Command
3
+ class Open < Base
4
+ def perform
5
+ Draft.new(ids: ids, repository: repository).open_with(&Editor)
6
+ end
7
+
8
+ private
9
+
10
+ def ids
11
+ params.ids || [repository.last_id]
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,9 @@
1
+ module Ncn
2
+ module Command
3
+ autoload :Base, "ncn/command/base"
4
+ autoload :Create, "ncn/command/create"
5
+ autoload :Help, "ncn/command/help"
6
+ autoload :List, "ncn/command/list"
7
+ autoload :Open, "ncn/command/open"
8
+ end
9
+ end
@@ -0,0 +1,12 @@
1
+ module Ncn
2
+ module CommandParams
3
+ class Base
4
+ attr_reader :arguments, :options
5
+
6
+ def initialize(arguments: [], options: {})
7
+ @arguments = arguments
8
+ @options = options
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,9 @@
1
+ module Ncn
2
+ module CommandParams
3
+ class Create < Base
4
+ def tags
5
+ options["--tags"]
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,13 @@
1
+ module Ncn
2
+ module CommandParams
3
+ class List < Base
4
+ def number
5
+ options["--number"]
6
+ end
7
+
8
+ def tags
9
+ options["--tags"]
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,19 @@
1
+ module Ncn
2
+ module CommandParams
3
+ class Open < Base
4
+ # @return [Array{Integer}, nil] array of note ids or nil if there are none
5
+ def ids
6
+ return unless arguments&.any?
7
+ arguments.map { normalize_note_id(_1) }
8
+ end
9
+
10
+ private
11
+
12
+ def normalize_note_id(value)
13
+ Integer(value)
14
+ rescue TypeError, ArgumentError
15
+ raise Error::NonValidNoteId
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,8 @@
1
+ module Ncn
2
+ module CommandParams
3
+ autoload :Base, "ncn/command_params/base"
4
+ autoload :Create, "ncn/command_params/create"
5
+ autoload :List, "ncn/command_params/list"
6
+ autoload :Open, "ncn/command_params/open"
7
+ end
8
+ end
@@ -0,0 +1,36 @@
1
+ module Ncn
2
+ class CommandResolver
3
+ COMMANDS = %w[
4
+ create
5
+ open
6
+ list
7
+ help
8
+ ].freeze
9
+
10
+ attr_reader :command
11
+
12
+ def initialize(command)
13
+ @command = command
14
+ end
15
+
16
+ def command_class
17
+ Kernel.const_get("Ncn::Command::#{classified_command}")
18
+ end
19
+
20
+ def params_class
21
+ Kernel.const_get("Ncn::CommandParams::#{classified_command}")
22
+ end
23
+
24
+ private
25
+
26
+ def classified_command
27
+ explicit_command.gsub(/(?:\b|_)([a-z])/) { $1.capitalize }
28
+ end
29
+
30
+ def explicit_command
31
+ return "help" unless command
32
+ raise "unknown command" unless COMMANDS.include?(command)
33
+ command
34
+ end
35
+ end
36
+ end
data/lib/ncn/draft.rb ADDED
@@ -0,0 +1,62 @@
1
+ module Ncn
2
+ class Draft
3
+ attr_reader :ids, :repository
4
+
5
+ def initialize(ids:, repository:)
6
+ @ids = ids
7
+ @repository = repository
8
+ end
9
+
10
+ def open_with
11
+ dump
12
+ yield file_name
13
+ load
14
+ FileUtils.rm_rf(file_name)
15
+ end
16
+
17
+ private
18
+
19
+ def dump
20
+ FileUtils.mkdir_p(File.dirname(file_name))
21
+ File.write(file_name, exported_notes)
22
+ end
23
+
24
+ def load
25
+ updated_note_ids = []
26
+
27
+ read_fragments.each do |fragment|
28
+ id, tags, body = parse_fragment(fragment)
29
+ updated_note_ids << id
30
+ repository.update(id, body: body, tags: tags)
31
+ end
32
+
33
+ (ids - updated_note_ids).each { repository.drop(_1) }
34
+ end
35
+
36
+ def read_fragments
37
+ File.read(file_name).split(/^--\s+(?=\d+),?/)[1..] || []
38
+ end
39
+
40
+ def parse_fragment(fragment)
41
+ fragment_tagline, body = fragment.split("\n", 2)
42
+ id, *tags = fragment_tagline.split(",").map(&:strip)
43
+ [Integer(id), tags, body]
44
+ end
45
+
46
+ def file_name
47
+ @file_name ||= File.join(repository.path, "edit", "#{ids.sort.join("_")}.md")
48
+ end
49
+
50
+ def exported_notes
51
+ notes.map { "#{tagline(_1)}\n#{_1.body}" }.join("\n\n") + "\n"
52
+ end
53
+
54
+ def tagline(note)
55
+ "-- #{[note.id].concat(note.uniq_tags).join(", ")}".strip
56
+ end
57
+
58
+ def notes
59
+ ids.map { repository.find(_1) }
60
+ end
61
+ end
62
+ end
data/lib/ncn/editor.rb ADDED
@@ -0,0 +1,8 @@
1
+ module Ncn
2
+ class Editor
3
+ def self.to_proc
4
+ editor = ENV["EDITOR"] || raise("$EDITOR not defined")
5
+ ->(file_name) { system("#{editor} \"#{file_name}\"") }
6
+ end
7
+ end
8
+ end
data/lib/ncn/error.rb ADDED
@@ -0,0 +1,31 @@
1
+ module Ncn
2
+ class Error < StandardError
3
+ RepoIsEmpty = Class.new(self)
4
+ NoteNotFound = Class.new(self)
5
+ NonValidNoteId = Class.new(self)
6
+
7
+ attr_reader :context
8
+
9
+ def initialize(context = {})
10
+ @context = context
11
+ end
12
+
13
+ def message
14
+ context[:message] || default_message
15
+ end
16
+
17
+ def to_s
18
+ message
19
+ end
20
+
21
+ def to_json
22
+ JSON.generate(context)
23
+ end
24
+
25
+ private
26
+
27
+ def default_message
28
+ self.class.name.split("::").last.gsub(/(?!\b)([A-Z])/, ' \1').downcase
29
+ end
30
+ end
31
+ end
data/lib/ncn/main.rb ADDED
@@ -0,0 +1,51 @@
1
+ module Ncn
2
+ class Main
3
+ DEFAULT_NOTES_PATH = "notes"
4
+
5
+ def run
6
+ code = 0
7
+ command.perform
8
+ rescue => e
9
+ puts e.message
10
+ puts e.backtrace.join("\n") if DEBUG
11
+ ensure
12
+ exit(code)
13
+ end
14
+
15
+ private
16
+
17
+ def command
18
+ resolver.command_class.new(repository: repository, params: command_params)
19
+ end
20
+
21
+ def command_params
22
+ resolver.params_class.new(options: options, arguments: arguments)
23
+ rescue NameError
24
+ nil
25
+ end
26
+
27
+ def repository
28
+ Repository.new(repository_path)
29
+ end
30
+
31
+ def repository_path
32
+ options.fetch(:path) { File.join(Dir.pwd, DEFAULT_NOTES_PATH) }
33
+ end
34
+
35
+ def options
36
+ cli_parser.options
37
+ end
38
+
39
+ def arguments
40
+ cli_parser.arguments
41
+ end
42
+
43
+ def resolver
44
+ @resolver ||= CommandResolver.new(cli_parser.command)
45
+ end
46
+
47
+ def cli_parser
48
+ @cli_parser ||= CliParser.new
49
+ end
50
+ end
51
+ end
data/lib/ncn/note.rb ADDED
@@ -0,0 +1,58 @@
1
+ module Ncn
2
+ class Note
3
+ MAX_TITLE_LENGTH = 80
4
+ OMISSION = "..."
5
+
6
+ attr_reader :id, :created
7
+ attr_accessor :tags, :body
8
+
9
+ def initialize(id:, created: nil, tags: nil, body: "")
10
+ @id = id
11
+ @created = created || Time.now
12
+ @tags = tags
13
+ @body = body
14
+ end
15
+
16
+ def title
17
+ first_line = body.to_s.strip.lines.first.to_s.strip.gsub(/^#+\s+/, "")
18
+ return first_line if first_line.length < MAX_TITLE_LENGTH
19
+ first_line[0..(MAX_TITLE_LENGTH - OMISSION.length.succ)] + OMISSION
20
+ end
21
+
22
+ def meta
23
+ {
24
+ "title" => title,
25
+ "tags" => csv(uniq_tags),
26
+ "created" => created.to_s
27
+ }
28
+ end
29
+
30
+ def uniq_tags
31
+ return [] unless tags
32
+ tags.uniq(&:downcase)
33
+ end
34
+
35
+ def path
36
+ NotePathBuilder.new(id: id, created: created).path
37
+ end
38
+
39
+ def to_h
40
+ {
41
+ id: id,
42
+ created: created,
43
+ tags: uniq_tags,
44
+ body: body
45
+ }
46
+ end
47
+
48
+ def to_s
49
+ "#{meta.to_yaml}---\n\n#{body.strip}"
50
+ end
51
+
52
+ private
53
+
54
+ def csv(values)
55
+ values.join(", ")
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,53 @@
1
+ module Ncn
2
+ class NoteLoader
3
+ attr_reader :file_name
4
+
5
+ def initialize(file_name)
6
+ @file_name = file_name
7
+ end
8
+
9
+ def load
10
+ Note.new(
11
+ id: id,
12
+ created: created,
13
+ tags: tags,
14
+ body: body
15
+ )
16
+ end
17
+
18
+ def id
19
+ @id ||= Integer(File.basename(file_name.split(".").first))
20
+ end
21
+
22
+ def created
23
+ value = meta["created"]
24
+ value.is_a?(Time) ? value : extract_approximate_timestamp
25
+ end
26
+
27
+ def extract_approximate_timestamp
28
+ year, month, day = file_name.split(File::SEPARATOR)[-4..-2]
29
+ Time.new(Integer(year), Integer(month), Integer(day), 0, 0, 0, 0)
30
+ end
31
+
32
+ def tags
33
+ meta["tags"].to_s.split(",").map(&:strip)
34
+ end
35
+
36
+ def meta
37
+ @meta ||= extract_meta
38
+ end
39
+
40
+ def extract_meta
41
+ result = YAML.safe_load(text, permitted_classes: [Time])
42
+ result.is_a?(Hash) ? result : {}
43
+ end
44
+
45
+ def body
46
+ text.gsub(/\A---(.|\n)*---\s*/, "").strip
47
+ end
48
+
49
+ def text
50
+ @text ||= File.read(file_name)
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,36 @@
1
+ module Ncn
2
+ class NotePathBuilder
3
+ attr_reader :id, :created
4
+
5
+ def initialize(created:, id:)
6
+ @id = id
7
+ @created = created
8
+ end
9
+
10
+ def path
11
+ File.join(*directory_names, "#{id}.md")
12
+ end
13
+
14
+ def directory_names
15
+ [year, month, day]
16
+ end
17
+
18
+ private
19
+
20
+ def year
21
+ created.year.to_s
22
+ end
23
+
24
+ def month
25
+ zero_indented(created.month)
26
+ end
27
+
28
+ def day
29
+ zero_indented(created.day)
30
+ end
31
+
32
+ def zero_indented(value)
33
+ format("%02d", value)
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,86 @@
1
+ module Ncn
2
+ class Repository
3
+ CACHE_PATH = "cache.json"
4
+
5
+ attr_reader :path
6
+
7
+ def initialize(path)
8
+ @path = path
9
+ end
10
+
11
+ def create(tags: [], body: "")
12
+ register_new_note(tags: tags, body: body).tap do |note|
13
+ cache.set(note.id, note.meta)
14
+ cache.set("last_id", note.id)
15
+ end
16
+ end
17
+
18
+ def list
19
+ cache.keys.filter { _1.match?(/^\d+$/) }
20
+ end
21
+
22
+ def find(id)
23
+ meta = cache.fetch(id) { raise Error::NoteNotFound }
24
+ created = Time.parse(meta.fetch("created"))
25
+ relative = NotePathBuilder.new(id: id, created: created).path
26
+ NoteLoader.new(File.join(path, relative)).load
27
+ end
28
+
29
+ def update(id, body: nil, tags: nil)
30
+ note = find(id)
31
+ note.body = body if body
32
+ note.tags = tags if tags
33
+ persist(note)
34
+ end
35
+
36
+ def drop(id)
37
+ meta = cache.fetch(id) { raise Error::NoteNotFound }
38
+ created = Time.parse(meta.fetch("created"))
39
+ path_builder = NotePathBuilder.new(id: id, created: created)
40
+ FileUtils.rm_rf(File.join(path, path_builder.path))
41
+ drop_empty_directories(path_builder.directory_names)
42
+ cache.unset(id)
43
+ end
44
+
45
+ def note_path(note)
46
+ File.join(path, note.path)
47
+ end
48
+
49
+ # @return [Integer] last cached note id; 0 means the repository is empty
50
+ def last_id
51
+ cache.fetch("last_id", 0)
52
+ end
53
+
54
+ private
55
+
56
+ def drop_empty_directories(directory_names)
57
+ year, month, day = directory_names
58
+
59
+ directories = [
60
+ File.join(path, year, month, day),
61
+ File.join(path, year, month),
62
+ File.join(path, year)
63
+ ]
64
+
65
+ directories.each do |directory_path|
66
+ break unless Dir.empty?(directory_path)
67
+ Dir.rmdir(directory_path)
68
+ end
69
+ end
70
+
71
+ # TODO: Make this operation atomic
72
+ def register_new_note(tags:, body:)
73
+ Note.new(id: last_id.succ, tags: tags, body: body).tap { persist(_1) }
74
+ end
75
+
76
+ def persist(note)
77
+ full_path = File.join(path, note.path)
78
+ FileUtils.mkdir_p(File.dirname(full_path))
79
+ File.write(full_path, note)
80
+ end
81
+
82
+ def cache
83
+ @cache ||= Cache.new(File.join(path, CACHE_PATH))
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ncn
4
+ VERSION = "0.1.0"
5
+ end
data/lib/ncn.rb ADDED
@@ -0,0 +1,25 @@
1
+ require "date"
2
+ require "fileutils"
3
+ require "getoptlong"
4
+ require "json"
5
+ require "time"
6
+ require "yaml"
7
+
8
+ require_relative "ncn/version"
9
+
10
+ module Ncn
11
+ autoload :Cache, "ncn/cache"
12
+ autoload :CliParser, "ncn/cli_parser"
13
+ autoload :Command, "ncn/command"
14
+ autoload :CommandParams, "ncn/command_params"
15
+ autoload :CommandResolver, "ncn/command_resolver"
16
+ autoload :Draft, "ncn/draft"
17
+ autoload :Editor, "ncn/editor"
18
+ autoload :Error, "ncn/error"
19
+ autoload :Note, "ncn/note"
20
+ autoload :NoteLoader, "ncn/note_loader"
21
+ autoload :NotePathBuilder, "ncn/note_path_builder"
22
+ autoload :Repository, "ncn/repository"
23
+ end
24
+
25
+ require_relative "ncn/main"
data/ncn.gemspec ADDED
@@ -0,0 +1,35 @@
1
+ require_relative "lib/ncn/version"
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "ncn"
5
+ spec.version = Ncn::VERSION
6
+ spec.authors = ["Alex Musayev"]
7
+ spec.email = ["alex.musayev@gmail.com"]
8
+
9
+ spec.summary = "Personal notes management tool"
10
+ spec.description = ""
11
+ spec.homepage = "https://github.com/dreikanter/ncn"
12
+ spec.license = "MIT"
13
+ spec.required_ruby_version = ">= 3.0.0"
14
+ spec.metadata["homepage_uri"] = spec.homepage
15
+ spec.metadata["source_code_uri"] = spec.homepage
16
+ spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/main/CHANGELOG.md"
17
+
18
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
19
+ `git ls-files -z`.split("\x0").reject do |f|
20
+ (f == __FILE__) || f.match(%r{\A(?:spec|\.git)})
21
+ end
22
+ end
23
+
24
+ spec.bindir = "bin"
25
+ spec.executables = ["ncn"]
26
+ spec.require_paths = ["lib"]
27
+
28
+ spec.add_development_dependency "amazing_print", "~> 1.4"
29
+ spec.add_development_dependency "pry", "~> 0.14"
30
+ spec.add_development_dependency "pry-byebug", "~> 3.9"
31
+ spec.add_development_dependency "rake", "~> 13.0"
32
+ spec.add_development_dependency "rspec", "~> 3.11"
33
+ spec.add_development_dependency "standard", "~> 1.8"
34
+ spec.add_development_dependency "timecop", "~> 0.9.5"
35
+ end
metadata ADDED
@@ -0,0 +1,185 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ncn
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Alex Musayev
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2022-04-06 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: amazing_print
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.4'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.4'
27
+ - !ruby/object:Gem::Dependency
28
+ name: pry
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '0.14'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '0.14'
41
+ - !ruby/object:Gem::Dependency
42
+ name: pry-byebug
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.9'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.9'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '13.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '13.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.11'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.11'
83
+ - !ruby/object:Gem::Dependency
84
+ name: standard
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '1.8'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '1.8'
97
+ - !ruby/object:Gem::Dependency
98
+ name: timecop
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: 0.9.5
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: 0.9.5
111
+ description: ''
112
+ email:
113
+ - alex.musayev@gmail.com
114
+ executables:
115
+ - ncn
116
+ extensions: []
117
+ extra_rdoc_files: []
118
+ files:
119
+ - ".rspec"
120
+ - ".rubocop.yml"
121
+ - CHANGELOG.md
122
+ - CODE_OF_CONDUCT.md
123
+ - Gemfile
124
+ - Gemfile.lock
125
+ - LICENSE
126
+ - README.md
127
+ - Rakefile
128
+ - bin/console
129
+ - bin/ncn
130
+ - bin/setup
131
+ - docs/commands/create.md
132
+ - docs/commands/open.md
133
+ - docs/structure.md
134
+ - lib/ncn.rb
135
+ - lib/ncn/cache.rb
136
+ - lib/ncn/cli_parser.rb
137
+ - lib/ncn/command.rb
138
+ - lib/ncn/command/base.rb
139
+ - lib/ncn/command/create.rb
140
+ - lib/ncn/command/help.rb
141
+ - lib/ncn/command/list.rb
142
+ - lib/ncn/command/open.rb
143
+ - lib/ncn/command_params.rb
144
+ - lib/ncn/command_params/base.rb
145
+ - lib/ncn/command_params/create.rb
146
+ - lib/ncn/command_params/list.rb
147
+ - lib/ncn/command_params/open.rb
148
+ - lib/ncn/command_resolver.rb
149
+ - lib/ncn/draft.rb
150
+ - lib/ncn/editor.rb
151
+ - lib/ncn/error.rb
152
+ - lib/ncn/main.rb
153
+ - lib/ncn/note.rb
154
+ - lib/ncn/note_loader.rb
155
+ - lib/ncn/note_path_builder.rb
156
+ - lib/ncn/repository.rb
157
+ - lib/ncn/version.rb
158
+ - ncn.gemspec
159
+ homepage: https://github.com/dreikanter/ncn
160
+ licenses:
161
+ - MIT
162
+ metadata:
163
+ homepage_uri: https://github.com/dreikanter/ncn
164
+ source_code_uri: https://github.com/dreikanter/ncn
165
+ changelog_uri: https://github.com/dreikanter/ncn/blob/main/CHANGELOG.md
166
+ post_install_message:
167
+ rdoc_options: []
168
+ require_paths:
169
+ - lib
170
+ required_ruby_version: !ruby/object:Gem::Requirement
171
+ requirements:
172
+ - - ">="
173
+ - !ruby/object:Gem::Version
174
+ version: 3.0.0
175
+ required_rubygems_version: !ruby/object:Gem::Requirement
176
+ requirements:
177
+ - - ">="
178
+ - !ruby/object:Gem::Version
179
+ version: '0'
180
+ requirements: []
181
+ rubygems_version: 3.3.4
182
+ signing_key:
183
+ specification_version: 4
184
+ summary: Personal notes management tool
185
+ test_files: []