From 8a87a8e001909e6caef03d9302fdbb17b7ac6bf8 Mon Sep 17 00:00:00 2001 From: Venkat Dinavahi Date: Fri, 24 Mar 2017 15:42:10 -0400 Subject: [PATCH 01/11] removed stuff --- Gemfile | 3 - Gemfile.lock | 53 ------ README.md | 70 -------- Rakefile | 5 - bin/code | 139 --------------- code.gemspec | 29 ---- code.rdoc | 5 - lib/code.rb | 4 - lib/code/branch.rb | 146 ---------------- lib/code/file_list.rb | 25 --- lib/code/git.rb | 163 ------------------ lib/code/match_scorer/adaptive.rb | 18 -- lib/code/match_scorer/base.rb | 22 --- .../match_scorer/contains_all_patterns.rb | 13 -- .../contains_patterns_in_order.rb | 14 -- lib/code/system.rb | 63 ------- lib/code/version.rb | 3 - spec/code/git_spec.rb | 88 ---------- spec/support/git_extras.rb | 25 --- 19 files changed, 888 deletions(-) delete mode 100644 Gemfile delete mode 100644 Gemfile.lock delete mode 100644 README.md delete mode 100644 Rakefile delete mode 100755 bin/code delete mode 100644 code.gemspec delete mode 100644 code.rdoc delete mode 100644 lib/code.rb delete mode 100644 lib/code/branch.rb delete mode 100644 lib/code/file_list.rb delete mode 100644 lib/code/git.rb delete mode 100644 lib/code/match_scorer/adaptive.rb delete mode 100644 lib/code/match_scorer/base.rb delete mode 100644 lib/code/match_scorer/contains_all_patterns.rb delete mode 100644 lib/code/match_scorer/contains_patterns_in_order.rb delete mode 100644 lib/code/system.rb delete mode 100644 lib/code/version.rb delete mode 100644 spec/code/git_spec.rb delete mode 100644 spec/support/git_extras.rb diff --git a/Gemfile b/Gemfile deleted file mode 100644 index a80c363..0000000 --- a/Gemfile +++ /dev/null @@ -1,3 +0,0 @@ -source 'https://rubygems.org' -ruby '2.1.1' -gemspec diff --git a/Gemfile.lock b/Gemfile.lock deleted file mode 100644 index 47ede46..0000000 --- a/Gemfile.lock +++ /dev/null @@ -1,53 +0,0 @@ -PATH - remote: . - specs: - code (0.0.1) - gli (= 2.8.0) - hub - -GEM - remote: https://rubygems.org/ - specs: - aruba (0.5.3) - childprocess (>= 0.3.6) - cucumber (>= 1.1.1) - rspec-expectations (>= 2.7.0) - builder (3.2.2) - childprocess (0.3.9) - ffi (~> 1.0, >= 1.0.11) - cucumber (1.3.8) - builder (>= 2.1.2) - diff-lcs (>= 1.1.3) - gherkin (~> 2.12.1) - multi_json (>= 1.7.5, < 2.0) - multi_test (>= 0.0.2) - diff-lcs (1.2.4) - ffi (1.9.0) - gherkin (2.12.1) - multi_json (~> 1.3) - gli (2.8.0) - hub (1.10.6) - json (1.8.0) - multi_json (1.8.0) - multi_test (0.0.2) - rake (10.1.0) - rdoc (4.0.1) - json (~> 1.4) - rspec (2.14.1) - rspec-core (~> 2.14.0) - rspec-expectations (~> 2.14.0) - rspec-mocks (~> 2.14.0) - rspec-core (2.14.5) - rspec-expectations (2.14.2) - diff-lcs (>= 1.1.3, < 2.0) - rspec-mocks (2.14.3) - -PLATFORMS - ruby - -DEPENDENCIES - aruba - code! - rake - rdoc - rspec diff --git a/README.md b/README.md deleted file mode 100644 index 93d77b6..0000000 --- a/README.md +++ /dev/null @@ -1,70 +0,0 @@ -[![Build Status](https://travis-ci.org/coderly/code.png)](https://travis-ci.org/coderly/code) -[![Code Climate](https://codeclimate.com/repos/5247675a89af7e537504d86d/badges/ed3e86a8e88092669654/gpa.png)](https://codeclimate.com/repos/5247675a89af7e537504d86d/feed) - -Code: The Coderly Toolbelt -================== - -`code` is a command line tool that automates our Coderly development workflow. - -`code` is best aliased as `c`, so you can type `$ c ` in the shell. - - -Installation ------------- - -Dependencies: - -* **git 1.7.3** or newer -* **Ruby 2.0** or newer -* **[hub](https://github.com/github/hub)** - -Install hub, for example on OSX: -~~~ sh -$ brew install hub -~~~ - -Run hub once in an active git directory to add your credentials -~~~ sh -$ hub fetch -~~~ - -Clone the repository to a directory of your choice and run bundle install -~~~ sh -$ git clone git@github.com:coderly/code.git -$ cd code -$ bundle install -~~~ - -Add the bin directory to the load paths by opening your `.bash_profile` and ensure you have the following -~~~ sh -PATH=$PATH:$HOME/path-you-cloned-code-to/code/bin -export PATH #Add this if it doesn't already exist -~~~ - -New Feature Workflow ------------- -1. Create a new feature branch -~~~ sh -$ code start name of my feature -~~~ -or equivalently -~~~ sh -$ code start name-of-my-feature -~~~ - -2. When you are ready, publish your code in a pull request -~~~ sh -$ code publish my pull request message -~~~ -Your pull request will be opened up in the browser - -3. Ask someone to review your code by referencing them in a comment in the pull request - -4. When someone gives you a :thumbsup: you can merge it from the pull request page. - * Make sure that the tests are passing. - * If the code can't be automatically merged, merge development onto your branch and resolve the conflicts. - -5. After the code has been merged type the following command which deletes your feature branch and updates your development branch -```sh -$ code finish -``` diff --git a/Rakefile b/Rakefile deleted file mode 100644 index 70a846d..0000000 --- a/Rakefile +++ /dev/null @@ -1,5 +0,0 @@ -require 'rspec/core/rake_task' - -RSpec::Core::RakeTask.new(:spec) - -task :default => :spec diff --git a/bin/code b/bin/code deleted file mode 100755 index 0910d54..0000000 --- a/bin/code +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/env ruby - -$: << File.join(File.dirname(__FILE__), '..', 'lib') # while this is still in development - -require 'gli' -begin # XXX: Remove this begin/rescue before distributing your app -require 'code' -rescue LoadError - STDERR.puts "In development, you need to use `bundle exec bin/code` to run your app" - STDERR.puts "At install-time, RubyGems will make sure lib, etc. are in the load path" - STDERR.puts "Feel free to remove this message from bin/code now" - exit 64 -end - -require 'code/git' -require 'code/branch' -require 'code/file_list' -require 'code/system' - -include GLI::App - -program_desc 'The Coderly Toolbelt' - -version Code::VERSION - -desc 'Describe some switch here' -switch [:s,:switch] - -desc 'Create a new feature branch' -arg_name 'The name of the feature' -command :start do |c| - c.action do |global_options, options, args| - feature_name = args.join('-') - $git.start feature_name - end -end - -desc 'Upload your feature branch to GitHub' -command :publish, :pr do |c| - c.switch [:master], desc: 'Make the pull request based off the master branch' - c.action do |global_options, options, args| - message = args.join(' ') - - base_branch = nil - base_branch = Code::Branch.master if options[:master] - - $git.publish(branch: Code::Branch.current, base: base_branch, message: message) - end -end - -desc "Push your current branch" -command :push, :p do |c| - c.action do |global_options, options, branch_name| - $git.push - end -end - -desc "Quickly create a pull request from your changes on development." -command :hotfix, :fix do |c| - c.action do |global_options, options, args| - hotfix_name = args.join('-') - $git.hotfix hotfix_name - end -end - -desc 'Cleanup after a feature has been merged through GitHub' -command :finish do |c| - c.action do |global_options, options, args| - $git.finish - end -end - -desc 'Delete the branch you are working on and switch back to development' -command :cancel do |c| - c.action do |global_options, options, args| - $git.cancel - end -end - -desc 'Switch to a branch. You can use sub-commands.' -command :switch, :s do |c| - c.action do |global_options, options, args| - $git.switch(*args) - end -end - -desc 'Deploy to production' -command :production do |c| - c.action do |global_options, options, args| - end -end - -desc 'List all the files in the current directory with the patterns' -command :files do |c| - c.action do |global_options, options, patterns| - puts FileList.new.matching(patterns) - end -end - -desc 'Clean up by deleting old branches' -command :clean do |c| - c.action do |global_options, options, patterns| - puts "Deleting local merged branches..." - Code::Branch.merged.each do |branch| - branch.delete! - end - puts "Done!" - - puts "Pruning remote branches that don't exist anymore..." - $git.prune_remote_branches - puts "Done!" - end -end - -desc 'List the merged branches' -command :merged do |c| - c.action do |global_options, options, patterns| - puts Code::Branch.merged - end -end - -pre do |global, command, options, args| - $git = Code::Git.new - true -end - -post do |global,command,options,args| - # Post logic here - # Use skips_post before a command to skip this - # block on that command only -end - -on_error do |exception| - # Error logic here - # return false to skip default error handling - true -end - -exit run(ARGV) diff --git a/code.gemspec b/code.gemspec deleted file mode 100644 index a0f65f8..0000000 --- a/code.gemspec +++ /dev/null @@ -1,29 +0,0 @@ -# Ensure we require the local version and not one we might have installed already -require File.join([File.dirname(__FILE__),'lib','code','version.rb']) -spec = Gem::Specification.new do |s| - s.name = 'code' - s.version = Code::VERSION - s.author = 'Venkat' - s.email = 'venkat@coderly.com' - s.homepage = 'http://www.coderly.com' - s.platform = Gem::Platform::RUBY - s.summary = 'Our command line toolbelt for common tasks' - -# Add your other files here if you make them - s.files = %w( - bin/code - lib/code/version.rb - lib/code.rb - ) - - s.require_paths << 'lib' - s.bindir = 'bin' - s.executables << 'code' - s.add_development_dependency('rake') - s.add_development_dependency('rdoc') - s.add_development_dependency('aruba') - s.add_development_dependency('rspec') - - s.add_runtime_dependency('gli','2.8.0') - s.add_runtime_dependency('hub') -end diff --git a/code.rdoc b/code.rdoc deleted file mode 100644 index eb6d9d5..0000000 --- a/code.rdoc +++ /dev/null @@ -1,5 +0,0 @@ -= code - -Generate this with - code rdoc -After you have described your command line interface \ No newline at end of file diff --git a/lib/code.rb b/lib/code.rb deleted file mode 100644 index 55ff41d..0000000 --- a/lib/code.rb +++ /dev/null @@ -1,4 +0,0 @@ -require 'code/version.rb' - -# Add requires for other files you add to your project here, so -# you just need to require this one file in your bin file diff --git a/lib/code/branch.rb b/lib/code/branch.rb deleted file mode 100644 index 8d13ab9..0000000 --- a/lib/code/branch.rb +++ /dev/null @@ -1,146 +0,0 @@ -module Code - - class Branch - - ProtectedBranchError = Class.new(StandardError) - PrivateBranchError = Class.new(StandardError) - - MASTER_BRANCH_NAME = 'master' - DEVELOPMENT_BRANCH_NAME = 'development' - PROTECTED_BRANCH_NAMES = %w{master development} - - def self.all_names - System.result('git branch').strip.lines.map { |line| line.gsub(/\s|\*/, '') } - end - - def self.all - all_names.map { |name| new(name) } - end - - def self.coerce_patterns(*patterns) - patterns.flatten.join(' ').split(' ') - end - - def self.matching(*patterns) - patterns = coerce_patterns(patterns) - all.find { |b| b.matches? *patterns } - end - - def self.exists?(branch_name) - new(branch_name).exists? - end - - def self.merged - clean_branch = lambda { |o| o.gsub('*', '').strip } - lines = System.result('git branch --merged development') - branch_names = lines.split("\n").map(&clean_branch) - branch_names = branch_names - ['development', 'master'] - branch_names.map { |name| new(name) } - end - - def self.current - name = System.result('git symbolic-ref HEAD').split('/')[-1] - new(name) - end - - def self.development - new DEVELOPMENT_BRANCH_NAME - end - - def self.master - new MASTER_BRANCH_NAME - end - - def self.create(branch_name) - System.call "branch #{branch_name}" - Branch.new(branch_name) - end - - def self.find(branch_name) - new(branch_name) - end - - def initialize(name) - @name = name - end - - def ==(branch) - name == branch.name - end - - def matches? *patterns - patterns.all? { |p| name.downcase.include? p.downcase } - end - - def exists? - System.result("git show-ref refs/heads/#{name}") != '' - end - - def development? - name == DEVELOPMENT_BRANCH_NAME - end - - def master? - name == MASTER_BRANCH_NAME - end - - def protected? - PROTECTED_BRANCH_NAMES.include? name - end - - def feature? - not protected? - end - - def delete!(force: false) - authorize_delete! - - flag = force ? '-D' : '-d' - System.call "branch #{flag} #{name}" - end - - def delete_remote! - authorize_delete! - - System.call "push origin :#{name}" - end - - def push - ensure_public! - System.call "push origin #{name}:#{name}" - end - - def pull - System.call "pull origin #{name}:#{name}" - end - - def checkout - System.call "checkout #{name}" - self - end - - def authorize_delete! - raise ProtectedBranchError, "The #{name} branch is protected" if protected? - end - - def message - name.gsub('-', ' ').capitalize - end - - def private? - !! name.match(/-local$/) - end - - def hotfix? - !! name.match(/^hotfix-/) - end - - def ensure_public! - raise PrivateBranchError, "#{name} is a private branch" if private? - end - - attr_reader :name - alias_method :to_s, :name - - end -end diff --git a/lib/code/file_list.rb b/lib/code/file_list.rb deleted file mode 100644 index 0132412..0000000 --- a/lib/code/file_list.rb +++ /dev/null @@ -1,25 +0,0 @@ -require 'code/match_scorer/adaptive' - -class FileList - include Enumerable - - MATCHING = lambda { |o| o > 0 } - - def initialize(base_path = '.') - @base_path = base_path - end - - def each(&block) - Dir['**/**'].each(&block) - end - - def matching(*patterns) - scorer = MatchScorer::Adaptive.new(*patterns) - select { |p| scorer.score(p) > 0 }.sort { |a, b| scorer.score(a) <=> scorer.score(b) } - end - - private - - attr_reader :base_path - -end \ No newline at end of file diff --git a/lib/code/git.rb b/lib/code/git.rb deleted file mode 100644 index 7436a3d..0000000 --- a/lib/code/git.rb +++ /dev/null @@ -1,163 +0,0 @@ -require 'uri' - -require 'code/branch' -require 'code/system' - -module Code - - class Git - - NotOnFeatureBranchError = Class.new(StandardError) - UncommittedChangesError = Class.new(StandardError) - FeatureExistsError = Class.new(StandardError) - - def path - Dir.pwd - end - - def start(feature) - raise FeatureExistsError, "Branch #{feature} already exists" if Branch.exists?(feature) - - with_stash do - development_branch.checkout unless current_branch.development? - development_branch.pull - - Branch.create(feature).checkout - end - end - - def stash - System.call('stash') - end - - def unstash - System.call('stash pop') - end - - def with_stash - if uncommitted_changes? - stash - yield - unstash - else - yield - end - end - - def hotfix(name) - name = "hotfix-#{name}" - raise FeatureExistsError, "Branch #{name} already exists" if Branch.exists?(name) - - with_stash do - master_branch.checkout unless current_branch.master? - master_branch.pull - - Branch.create(name).checkout - end - end - - def switch(*patterns) - Branch.matching(*patterns).checkout - end - - def cancel - if current_branch.development? - puts "Nothing to cancel (already on #{development_branch})" - else - previous_branch = current_branch - checkout development_branch - previous_branch.delete!(force: true) - end - end - - def commit(message) - System.call 'add -A' - System.call "commit -m \"#{message}\"" - end - - def publish(branch:, base: nil, message: '') - raise NotOnFeatureBranchError, 'Must be on a feature branch to publish your code' unless current_branch.feature? - raise UncommittedChangesError, 'You have uncommitted changes' if uncommitted_changes? - - base = infer_base_branch(branch) if base.nil? - - branch.push - - System.open_in_browser pull_request(branch: branch, base: base, message: message) - end - - def push - current_branch.push - end - - def pull_request(branch:, base:, message: '') - message = branch.message if message.empty? - command = "hub pull-request -f \"#{message}\" -b #{main_repo}:#{base} -h #{main_repo}:#{branch}" - System.exec(command).strip - end - - def compare_in_browser(branch) - System.exec "hub compare #{branch}" - end - - def finish - branch = current_branch - - development_branch.checkout - fetch - development_branch.pull - - branch.delete! - end - - def uncommitted_changes? - System.result('git status --porcelain') != '' - end - - def checkout(branch_name) - Branch.matching(branch_name).checkout - end - - def fetch - System.call 'fetch' - end - - def current_branch - Branch.current - end - - def development_branch - Branch.development - end - - def master_branch - Branch.master - end - - def infer_base_branch(branch) - if branch.hotfix? - master_branch - else - development_branch - end - end - - def prune_remote_branches - System.call 'remote prune origin' - end - - def main_repo - main_repo_url[/:(\w+)\//,1] - end - - def main_repo_url - repo_url 'origin' - end - - def repo_url(name) - System.result("git ls-remote --get-url #{name}") - end - - end - -end diff --git a/lib/code/match_scorer/adaptive.rb b/lib/code/match_scorer/adaptive.rb deleted file mode 100644 index e4651fc..0000000 --- a/lib/code/match_scorer/adaptive.rb +++ /dev/null @@ -1,18 +0,0 @@ -require 'code/match_scorer/contains_patterns_in_order' -require 'code/match_scorer/contains_all_patterns' - -module MatchScorer - class Adaptive < Base - - SUBSCORER_CLASSES = [MatchScorer::ContainsAllPatterns, MatchScorer::ContainsPatternsInOrder] - - def score(string) - subscorers.inject(0) { |total, scorer| total + scorer.score(string).to_i } - end - - def subscorers - @subscorers ||= SUBSCORER_CLASSES.map { |k| k.new(patterns) } - end - - end -end \ No newline at end of file diff --git a/lib/code/match_scorer/base.rb b/lib/code/match_scorer/base.rb deleted file mode 100644 index 5030755..0000000 --- a/lib/code/match_scorer/base.rb +++ /dev/null @@ -1,22 +0,0 @@ -module MatchScorer - class Base - def initialize(*patterns) - @patterns = coerce_patterns(*patterns) - end - - def score(string) - raise NotImplementedError, "Must implement #{__method__} for #{self.class}" - end - - protected - - attr_reader :patterns - - private - - def coerce_patterns(*patterns) - Array(patterns).join(' ').split(' ') - end - - end -end diff --git a/lib/code/match_scorer/contains_all_patterns.rb b/lib/code/match_scorer/contains_all_patterns.rb deleted file mode 100644 index af4940f..0000000 --- a/lib/code/match_scorer/contains_all_patterns.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'code/match_scorer/base' - -module MatchScorer - class ContainsAllPatterns < Base - def score(string) - 2 if matches? string - end - - def matches?(string) - patterns.all? { |pattern| string.downcase.include? pattern.downcase } - end - end -end diff --git a/lib/code/match_scorer/contains_patterns_in_order.rb b/lib/code/match_scorer/contains_patterns_in_order.rb deleted file mode 100644 index ecca95c..0000000 --- a/lib/code/match_scorer/contains_patterns_in_order.rb +++ /dev/null @@ -1,14 +0,0 @@ -require 'code/match_scorer/base' - -module MatchScorer - class ContainsPatternsInOrder < Base - def score(string) - 4 if matches?(string) - end - - def matches?(string) - regexp_string = patterns.map { |p| Regexp.escape(p) }.join('.*') - Regexp.new(regexp_string) == string - end - end -end \ No newline at end of file diff --git a/lib/code/system.rb b/lib/code/system.rb deleted file mode 100644 index f107e5d..0000000 --- a/lib/code/system.rb +++ /dev/null @@ -1,63 +0,0 @@ -module Code - module System - extend self - - CommandFailedError = ::Class.new(StandardError) - - COLORS = {black: 30, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, teal: 36} - - def prompt(*args) - print(*args) - gets - end - - def error(message) - abort red(message) - end - - def open_in_browser(url) - open url if url =~ URI::regexp - end - - def open(item) - `open #{item}` - end - - def exec(script) - puts green(script) - result = %x[#{script}] - raise CommandFailedError, red("command failed: #{script}") if command_failed? - result - end - - def command_failed? - not $?.success? - end - - def puts(text) - Kernel.puts text - end - - def call(params) - exec "git #{params}" - end - - def result(script) - `#{script}`.strip - end - - def color(script, color) - value = COLORS[color] - "\033[0;#{value}m" + script + "\033[m" - end - - def green(script) - color script, :green - end - - def red(script) - color script, :red - end - - end -end diff --git a/lib/code/version.rb b/lib/code/version.rb deleted file mode 100644 index f51563e..0000000 --- a/lib/code/version.rb +++ /dev/null @@ -1,3 +0,0 @@ -module Code - VERSION = '0.0.1' -end diff --git a/spec/code/git_spec.rb b/spec/code/git_spec.rb deleted file mode 100644 index 170fe6c..0000000 --- a/spec/code/git_spec.rb +++ /dev/null @@ -1,88 +0,0 @@ -require 'code/git' -require 'code/branch' -require 'code/system' - -require_relative '../support/git_extras' - -require 'tmpdir' - -module Code - describe Git do - - let(:git) { Git.new } - let(:repo_path) { @repo_path } - - before(:all) do - Git.send :include, GitExtras - end - - before do - allow(System).to receive(:puts) - Git.setup_test_repo - end - - describe 'current_branch' do - let(:branch) { git.current_branch } - - subject { branch } - - it 'should currently be on the master branch' do - expect(branch.name).to eq 'master' - end - - context 'when creating a new branch' do - - before do - Branch.create 'test_branch' - end - - it 'should have the right branches' do - expect(Branch.all.count).to eq 2 - end - - it 'should have created the branch' do - expect(Branch.new('test_branch')).to exist - end - - context 'when deleting a branch' do - before do - Branch.matching('test_branch').delete! - end - - it 'should only have one branch left' do - expect(Branch.all.count).to eq 1 - end - - it 'should have deleted the branch' do - expect(Branch.new('test_branch')).to_not exist - end - end - - context 'when checking out a branch' do - before do - Branch.matching('test_branch').checkout - end - - it 'should have changed the branch' do - expect(Branch.current.name).to eq 'test_branch' - end - end - - end - - context 'when trying to delete a protected branch' do - - before do - Branch.create 'development' - end - - it 'should now be allowed' do - expect { Branch.matching('development').delete! }.to raise_error Branch::ProtectedBranchError - end - - end - - end - - end -end \ No newline at end of file diff --git a/spec/support/git_extras.rb b/spec/support/git_extras.rb deleted file mode 100644 index c83eac5..0000000 --- a/spec/support/git_extras.rb +++ /dev/null @@ -1,25 +0,0 @@ -require 'code/system' - -module Code - module GitExtras - - module ClassMethods - def setup_test_repo - repo_path = Dir.mktmpdir('codegit') - Dir.chdir repo_path - - System.call 'init' - System.call 'config user.email "test@hotmail.com"' - System.call 'config user.name "Chuck Norris"' - System.exec 'touch README' - System.call 'add -A' - System.call 'commit -m "initial commit"' - end - end - - def self.included(base) - base.extend(ClassMethods) - end - - end -end From b8c420db2bab7bd948fbfcc0798978d696cbb389 Mon Sep 17 00:00:00 2001 From: Venkat Dinavahi Date: Wed, 5 Jul 2017 13:18:50 -0400 Subject: [PATCH 02/11] added sloc to command line --- .gitignore | 21 ++++++++++ .travis.yml | 3 -- README.md | 19 +++++++++ config/config.exs | 17 ++++++++ lib/c.ex | 18 ++++++++ lib/cli.ex | 71 +++++++++++++++++++++++++++++++ lib/git.ex | 38 +++++++++++++++++ lib/github_api.ex | 84 +++++++++++++++++++++++++++++++++++++ lib/sloc.ex | 99 ++++++++++++++++++++++++++++++++++++++++++++ mix.exs | 26 ++++++++++++ mix.lock | 10 +++++ test/c_test.exs | 8 ++++ test/test_helper.exs | 1 + 13 files changed, 412 insertions(+), 3 deletions(-) create mode 100644 .gitignore delete mode 100644 .travis.yml create mode 100644 README.md create mode 100644 config/config.exs create mode 100644 lib/c.ex create mode 100644 lib/cli.ex create mode 100644 lib/git.ex create mode 100644 lib/github_api.ex create mode 100644 lib/sloc.ex create mode 100644 mix.exs create mode 100644 mix.lock create mode 100644 test/c_test.exs create mode 100644 test/test_helper.exs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..df81754 --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +# The directory Mix will write compiled artifacts to. +/_build + +# If you run "mix test --cover", coverage assets end up here. +/cover + +# The directory Mix downloads your dependencies sources to. +/deps + +# Where 3rd-party dependencies like ExDoc output generated docs. +/doc + +# If the VM crashes, it generates a dump, let's ignore it too. +erl_crash.dump + +# Also ignore archive artifacts (built via "mix archive.build"). +*.ez + +.DS_Store + +c diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index ec60a07..0000000 --- a/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: ruby -rvm: - - 2.1.1 \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..be551de --- /dev/null +++ b/README.md @@ -0,0 +1,19 @@ +# C + +**TODO: Add description** + +## Installation + +If [available in Hex](https://hex.pm/docs/publish), the package can be installed +by adding `c` to your list of dependencies in `mix.exs`: + +```elixir +def deps do + [{:c, "~> 0.1.0"}] +end +``` + +Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc) +and published on [HexDocs](https://hexdocs.pm). Once published, the docs can +be found at [https://hexdocs.pm/c](https://hexdocs.pm/c). + diff --git a/config/config.exs b/config/config.exs new file mode 100644 index 0000000..28e00d4 --- /dev/null +++ b/config/config.exs @@ -0,0 +1,17 @@ +use Mix.Config + +# config/config.exs +config :c, C.GitHub.Client, + adapter: Revolver.Adapters.Hackney, + host: "https://api.github.com", + headers: [ + {"accept", "application/vnd.github.v3+json"}, + {"content-type", "application/json"} + ] + +# Configure serializers for automatic encoding/decoding request/response bodies +config :revolver, + serializers: %{ + "application/json" => Poison, + "application/vnd.github.v3+json" => Poison + } diff --git a/lib/c.ex b/lib/c.ex new file mode 100644 index 0000000..5b5c3e3 --- /dev/null +++ b/lib/c.ex @@ -0,0 +1,18 @@ +defmodule C do + @moduledoc """ + Documentation for C. + """ + + @doc """ + Hello world. + + ## Examples + + iex> C.hello + :world + + """ + def hello do + :world + end +end diff --git a/lib/cli.ex b/lib/cli.ex new file mode 100644 index 0000000..9d85fa5 --- /dev/null +++ b/lib/cli.ex @@ -0,0 +1,71 @@ +defmodule C.CLI do + + def main(args) do + {_opts, args, _} = OptionParser.parse(args) + + [cmd | rest_args] = args + execute(cmd, rest_args) + end + + # @grep_opts ~w(--break --heading --line-number --ignore-case --color=always --all-match) + @grep_opts ~w(--ignore-case --color=always --all-match --name-only) + def execute("look", keywords) do + with {:ok, commits} <- rev_list(), + {:ok, lines} <- cmd_value("git", ["grep"] ++ @grep_opts ++ match_patterns(keywords) ++ commits) do + extract_file_names(lines) |> IO.inspect() + end + end + def execute("sloc", args) do + report = Sloc.get_report(get_path(args)) + IO.puts(Sloc.format_report(report)) + end + def execute("req", _) do + C.GitHub.API.list!() |> IO.inspect() + end + def execute("pwd", _), do: cmd("pwd") + + def get_path([]), do: File.cwd!() + def get_path([path]), do: path + + def extract_file_names(commit_files) do + commit_files + |> String.split("\n") + |> Enum.map(fn line -> + [sha, file] = String.split(line, ":") + %{file: file, sha: sha} + end) + |> group_by_map(&Map.get(&1, :file), &Map.get(&1, :sha)) + end + + def group_by_map(items, grouper, mapper) do + items + |> Enum.group_by(grouper) + |> Enum.map(fn {k, values} -> {k, Enum.map(values, mapper)} end) + end + + def cmd(command, args \\ []) do + case System.cmd(command, args, [into: IO.stream(:stdio, :line), stderr_to_stdout: true, parallelism: false]) do + {value, 0} -> {:ok, value} + {_, 1} -> :error + end + end + + def cmd_value(command, args) do + case System.cmd(command, args) do + {value, 0} -> {:ok, String.trim(value)} + {err, 1} -> {:error, err} + end + end + + def match_patterns(keywords) do + Enum.flat_map(keywords, fn k -> ["-e", k] end) + end + + def rev_list() do + with {rev_list, 0} <- System.cmd("git", ["rev-list", "--all"]) do + commits = rev_list |> String.trim() |> String.split("\n") + {:ok, commits} + end + end + +end diff --git a/lib/git.ex b/lib/git.ex new file mode 100644 index 0000000..7d11a3f --- /dev/null +++ b/lib/git.ex @@ -0,0 +1,38 @@ +defmodule C.Git do + + def current_branch() do + {:ok, "refs/heads/" <> branch_name} = cmd_value("git", ["symbolic-ref", "HEAD"]) + branch_name + end + + def create_pull_request do + {org, repo} = github_org_and_repo() + branch = current_branch() + C.GitHub.API.get_pull_requests(org: org, repo: repo, head: branch, base: "master") + end + + def github_org_and_repo() do + "git@github.com:" <> git_path = git_url("origin") + [org, repo] = git_path |> String.replace(~r/\.git$/, "") |> String.split("/") + {org, repo} + end + + def git_url(remote_name) do + with {:ok, url} <- cmd_value("git", ["ls-remote", "--get-url", remote_name]), do: url + end + + def set_config(key, value) do + cmd_value("git", ["config", "--global", key, value]) + end + def get_config(key) do + cmd_value("git", ["config", "--get", key]) + end + + def cmd_value(command, args) do + case System.cmd(command, args, cd: "/Users/venkat/Code/turtle/turtle-api") do + {value, 0} -> {:ok, String.trim(value)} + {err, 1} -> {:error, err} + end + end + +end diff --git a/lib/github_api.ex b/lib/github_api.ex new file mode 100644 index 0000000..824dd40 --- /dev/null +++ b/lib/github_api.ex @@ -0,0 +1,84 @@ +defmodule C.GitHub.Client do + use Revolver.Client, otp_app: :c +end + +defmodule C.GitHub.API do + import C.GitHub.Client + import Revolver.Conn + + @doc """ + Fetches a list of repos for the give username. + """ + def list! do + conn() |> get!("/users/venkatd/repos") + end + + def authorize! do + auth = get_username_password() + response = authorize_req(auth) |> post!("/authorizations") + + otp = IO.gets("Please specify two-factor auth code: ") |> String.trim() + + response = authorize_req(auth) + |> put_req_header("x-github-otp", otp) + |> post!("/authorizations") + + token = response.resp_body["token"] + + C.Git.set_config("code.github.token", token) + + IO.puts("Authorized with GitHub") + end + + def authorize(conn) do + case C.Git.get_config("code.github.token") do + {:ok, token} -> + put_req_header(conn, "authorization", "Bearer #{token}") + end + end + + def create_pull_request(opts) do + opts = Enum.into(opts, %{}) + do_create_pull_request(opts) + end + def do_create_pull_request(%{org: org, repo: repo, base: base, head: head}) do + params = %{ + "title" => "Amazing new feature", + "body" => "Please pull this in!", + "head" => head, + "base" => base + } + conn() + |> authorize() + |> put_req_body(params) + |> post!("/repos/#{org}/#{repo}/pulls") + end + + def get_pull_requests(opts) do + opts = Enum.into(opts, %{}) + do_get_pull_requests(opts) + end + def do_get_pull_requests(%{org: org, repo: repo, base: base, head: head}) do + conn() + |> authorize() + |> get!("/repos/#{org}/#{repo}/pulls?state=open&base=#{base}&head=#{head}") + end + + defp authorize_req(auth) do + conn() + |> put_req_header("authorization", generate_basic_auth_header(auth)) + |> put_req_body(%{"scopes" => ["repo"], "note" => "code cli"}) + end + + def get_username_password() do + # {"venkatd", "9gbAQFPhFhQqp2"} + username = IO.gets("username: ") + password = IO.gets("password: ") + {String.trim(username), String.trim(password)} + end + + def generate_basic_auth_header({username, password}) do + "Basic " <> Base.encode64(username <> ":" <> password) + end + +end diff --git a/lib/sloc.ex b/lib/sloc.ex new file mode 100644 index 0000000..ddbabd2 --- /dev/null +++ b/lib/sloc.ex @@ -0,0 +1,99 @@ +defmodule Sloc do + + defmodule Node do + defstruct [:path, :type, line_count: 0, children: %{}] + + def deep_map(%Node{type: :file}=node, func) do + func.(node) + end + def deep_map(%Node{type: :directory, children: children}=node, func) do + new_children = for {k, n} <- children, into: %{}, do: {k, deep_map(n, func)} + func.(%{node | children: new_children}) + end + end + + @path "../turtle/turtle-api/lib" + @whitelist ~w(.ex .exs .rb) + + def run do + report = get_report(@path) + IO.puts(format_report(report)) + end + + def format_report(node), do: format_report(node, 0) + def format_report(%Node{path: path, line_count: line_count, children: children}, depth) do + [ + String.duplicate(" ", depth), + Path.basename(path), " (", to_string(line_count), ")", + format_report(Map.values(children), depth + 1) + ] + end + def format_report(nodes, depth) when is_list(nodes) do + nodes + |> Enum.sort_by(fn n -> -n.line_count end) + |> Enum.map(fn n -> ["\n", format_report(n, depth + 1)] end) + end + + def get_report(path) do + get_tree(path) + |> Node.deep_map(&calculate_line_count/1) + |> Node.deep_map(&normalize_path(&1, path)) + |> Node.deep_map(&aggregate/1) + end + + def normalize_path(%Node{path: path}=node, root) do + %{node | path: Path.relative_to(path, root)} + end + + def calculate_line_count(%Node{type: :file, path: path}=node) do + %{node | line_count: line_count(path)} + end + def calculate_line_count(%Node{type: :directory}=node), do: node + + def aggregate(%Node{type: :file}=node), do: node + def aggregate(%Node{type: :directory, children: children}=node) do + line_count = children |> Map.values() |> Enum.map(&Map.get(&1, :line_count)) |> Enum.sum() + %{node | line_count: line_count} + end + + def get_tree(path) do + cond do + File.regular?(path) -> + %Node{type: :file, path: path} + File.dir?(path) -> + children = for subpath <- get_filtered_subpaths(path), into: %{} do + {Path.basename(subpath), get_tree(subpath)} + end + %Node{type: :directory, path: path, children: children} + true -> nil + end + end + + def line_count(filepath) do + File.stream!(filepath) + |> Stream.reject(&Regex.match?(~r/^\s*$/, &1)) + |> Enum.count() + end + + def get_filtered_subpaths(path) do + path + |> File.ls!() + |> Enum.map(&Path.join(path, &1)) + |> Enum.reject(&is_dotfile?/1) + |> Enum.filter(fn p -> + File.dir?(p) || has_ext?(p, @whitelist) + end) + end + + defp is_dotfile?(path) do + case Path.basename(path) do + "." <> _ -> true + _ -> false + end + end + + defp has_ext?(path, extensions) do + Enum.member?(extensions, Path.extname(path)) + end + +end diff --git a/mix.exs b/mix.exs new file mode 100644 index 0000000..90925e4 --- /dev/null +++ b/mix.exs @@ -0,0 +1,26 @@ +defmodule C.Mixfile do + use Mix.Project + + def project do + [app: :c, + version: "0.1.0", + elixir: "~> 1.4", + build_embedded: Mix.env == :prod, + start_permanent: Mix.env == :prod, + escript: [main_module: C.CLI], + deps: deps()] + end + + def application do + [extra_applications: [:logger]] + end + + defp deps do + [ + {:revolver, github: "scrogson/revolver", ref: "master"}, + {:hackney, "1.6.1"}, + {:poison, "~> 3.0"} + ] + end + +end diff --git a/mix.lock b/mix.lock new file mode 100644 index 0000000..0b8360a --- /dev/null +++ b/mix.lock @@ -0,0 +1,10 @@ +%{"certifi": {:hex, :certifi, "0.4.0", "a7966efb868b179023618d29a407548f70c52466bf1849b9e8ebd0e34b7ea11f", [:rebar3], []}, + "hackney": {:hex, :hackney, "1.6.1", "ddd22d42db2b50e6a155439c8811b8f6df61a4395de10509714ad2751c6da817", [:rebar3], [{:certifi, "0.4.0", [hex: :certifi, optional: false]}, {:idna, "1.2.0", [hex: :idna, optional: false]}, {:metrics, "1.0.1", [hex: :metrics, optional: false]}, {:mimerl, "1.0.2", [hex: :mimerl, optional: false]}, {:ssl_verify_fun, "1.1.0", [hex: :ssl_verify_fun, optional: false]}]}, + "idna": {:hex, :idna, "1.2.0", "ac62ee99da068f43c50dc69acf700e03a62a348360126260e87f2b54eced86b2", [:rebar3], []}, + "metrics": {:hex, :metrics, "1.0.1", "25f094dea2cda98213cecc3aeff09e940299d950904393b2a29d191c346a8486", [:rebar3], []}, + "mime": {:hex, :mime, "1.1.0", "01c1d6f4083d8aa5c7b8c246ade95139620ef8effb009edde934e0ec3b28090a", [:mix], []}, + "mimerl": {:hex, :mimerl, "1.0.2", "993f9b0e084083405ed8252b99460c4f0563e41729ab42d9074fd5e52439be88", [:rebar3], []}, + "plug": {:hex, :plug, "1.3.4", "b4ef3a383f991bfa594552ded44934f2a9853407899d47ecc0481777fb1906f6", [:mix], [{:cowboy, "~> 1.0.1 or ~> 1.1", [hex: :cowboy, optional: true]}, {:mime, "~> 1.0", [hex: :mime, optional: false]}]}, + "poison": {:hex, :poison, "3.1.0", "d9eb636610e096f86f25d9a46f35a9facac35609a7591b3be3326e99a0484665", [:mix], []}, + "revolver": {:git, "https://github.com/scrogson/revolver.git", "174f1049ba8beae65e53672b19d526bbba761a6d", [ref: "master"]}, + "ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.0", "edee20847c42e379bf91261db474ffbe373f8acb56e9079acb6038d4e0bf414f", [:make, :rebar], []}} diff --git a/test/c_test.exs b/test/c_test.exs new file mode 100644 index 0000000..2b38e02 --- /dev/null +++ b/test/c_test.exs @@ -0,0 +1,8 @@ +defmodule CTest do + use ExUnit.Case + doctest C + + test "the truth" do + assert 1 + 1 == 2 + end +end diff --git a/test/test_helper.exs b/test/test_helper.exs new file mode 100644 index 0000000..869559e --- /dev/null +++ b/test/test_helper.exs @@ -0,0 +1 @@ +ExUnit.start() From d9e0cca8e961d740afd558c2940af0e4864a9581 Mon Sep 17 00:00:00 2001 From: Venkat Dinavahi Date: Sun, 27 Aug 2017 18:13:40 -0400 Subject: [PATCH 03/11] updated look command to be useful --- lib/cli.ex | 62 +++++++++-------------------- lib/git.ex | 112 +++++++++++++++++++++++++++++++++++++++++++++++----- lib/sloc.ex | 2 +- lib/util.ex | 17 ++++++++ 4 files changed, 139 insertions(+), 54 deletions(-) create mode 100644 lib/util.ex diff --git a/lib/cli.ex b/lib/cli.ex index 9d85fa5..1ba1df1 100644 --- a/lib/cli.ex +++ b/lib/cli.ex @@ -1,4 +1,5 @@ defmodule C.CLI do + import C.Util, only: [cmd_value: 2, cmd: 1, cmd: 2] def main(args) do {_opts, args, _} = OptionParser.parse(args) @@ -7,65 +8,40 @@ defmodule C.CLI do execute(cmd, rest_args) end - # @grep_opts ~w(--break --heading --line-number --ignore-case --color=always --all-match) - @grep_opts ~w(--ignore-case --color=always --all-match --name-only) def execute("look", keywords) do - with {:ok, commits} <- rev_list(), - {:ok, lines} <- cmd_value("git", ["grep"] ++ @grep_opts ++ match_patterns(keywords) ++ commits) do - extract_file_names(lines) |> IO.inspect() - end + C.Git.search_history(keywords) + |> format_look() + |> IO.puts() end def execute("sloc", args) do report = Sloc.get_report(get_path(args)) IO.puts(Sloc.format_report(report)) end def execute("req", _) do - C.GitHub.API.list!() |> IO.inspect() + C.GitHub.API.list!() + end + def execute("pr", _) do + end + def execute("branch", _) do + args = ~w{for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'} + cmd("git", ["status"]) end def execute("pwd", _), do: cmd("pwd") def get_path([]), do: File.cwd!() def get_path([path]), do: path - def extract_file_names(commit_files) do - commit_files - |> String.split("\n") - |> Enum.map(fn line -> - [sha, file] = String.split(line, ":") - %{file: file, sha: sha} - end) - |> group_by_map(&Map.get(&1, :file), &Map.get(&1, :sha)) + def format_look(entries) do + Enum.map_join(entries, "\n\n", &format_entry/1) end - - def group_by_map(items, grouper, mapper) do - items - |> Enum.group_by(grouper) - |> Enum.map(fn {k, values} -> {k, Enum.map(values, mapper)} end) - end - - def cmd(command, args \\ []) do - case System.cmd(command, args, [into: IO.stream(:stdio, :line), stderr_to_stdout: true, parallelism: false]) do - {value, 0} -> {:ok, value} - {_, 1} -> :error - end - end - - def cmd_value(command, args) do - case System.cmd(command, args) do - {value, 0} -> {:ok, String.trim(value)} - {err, 1} -> {:error, err} - end - end - - def match_patterns(keywords) do - Enum.flat_map(keywords, fn k -> ["-e", k] end) + def format_entry(%{file: file, commit: %{hash: hash, author_date: author_date, subject: subject}, matches: matches}) do + matches = Enum.map_join(matches, "\n", fn {line, text} -> to_string(line) <> ":" <> text end) + file <> ":" <> hash <> "\n" <> format_date(author_date) <> " " <> subject <> "\n" <> matches end - def rev_list() do - with {rev_list, 0} <- System.cmd("git", ["rev-list", "--all"]) do - commits = rev_list |> String.trim() |> String.split("\n") - {:ok, commits} - end + def format_date(date) do + [date, _time] = String.split(date, "T", parts: 2) + date end end diff --git a/lib/git.ex b/lib/git.ex index 7d11a3f..17897b0 100644 --- a/lib/git.ex +++ b/lib/git.ex @@ -1,20 +1,115 @@ defmodule C.Git do + import C.Util, only: [cmd_value: 2] + + defmodule Commit do + defstruct [:hash, :subject, :body, + :author_date, :author_email, :author_name, + :committer_date, :committer_email, :comitter_name] + end + defmodule GrepEntry do + defstruct [:commit, :file, :matches] + end def current_branch() do {:ok, "refs/heads/" <> branch_name} = cmd_value("git", ["symbolic-ref", "HEAD"]) branch_name end + # @grep_opts ~w(--break --heading --line-number --ignore-case --color=always --all-match) + @grep_opts ~w(--ignore-case --all-match --heading --break --line-number) + def search_history(keywords) do + with {:ok, commits} <- list_commits(), + commit_hashes <- Enum.map(commits, &Map.get(&1, :hash)), + {:ok, raw} <- cmd_value("git", ["grep"] ++ @grep_opts ++ match_patterns(keywords) ++ commit_hashes), + entries <- parse_search_history(raw, commits), + do: filter_to_latest(entries) + end + def parse_search_history(raw, commits) do + commits_by_hash = for c <- commits, into: %{}, do: {c.hash, c} + raw + |> String.split("\n\n") + |> Enum.map(&parse_grep_entry/1) + |> Enum.map(fn %GrepEntry{commit: hash}=entry -> + %{entry | commit: Map.get(commits_by_hash, hash) } + end) + end + def filter_to_latest(entries) do + entries + |> Enum.group_by(&Map.get(&1, :file)) + |> Enum.map(fn {_k, items} -> + Enum.max_by(items, fn e -> e.commit.author_date end) + end) + |> Enum.sort_by(fn e -> e.commit.author_date end, &>=/2) + end + + @commit_fields %{hash: "%H", subject: "%s", body: "%b", + author_date: "%aI", author_email: "%ae", author_name: "%an", committer_date: "%cI", + committer_email: "%ce", committer_name: "%cn"} + @delimiter "$$;;" + + def list_commits() do + fields = [:hash, :author_date, :author_name, :subject] + format = rev_parse_format(fields) + filter = ["head"] + with {:ok, commit_string} <- cmd_value("git", ["rev-list"] ++ filter ++ ["--format=#{format}"]), + do: {:ok, parse_commits(commit_string, fields)} + end + + def parse_commits(commit_string, fields) do + commit_string + |> String.split("\n") + |> Enum.reject(fn + "commit " <> _ -> true + _ -> false + end) + |> Enum.map(&parse_commit(&1, fields)) + end + + def parse_commit(line, fields) do + values = String.split(line, @delimiter) + attrs = Enum.zip(fields, values) |> Enum.into([]) + struct(Commit, attrs) + end + + def parse_grep_entry(entry_string) do + [header | raw_matches] = String.split(entry_string, "\n") + [commit, file] = String.split(header, ":", parts: 2) + matches = Enum.map(raw_matches, fn m -> + [line, text] = String.split(m, ":", parts: 2) + {String.to_integer(line), text} + end) + %GrepEntry{commit: commit, file: file, matches: matches} + end + + def rev_parse_format(fields) do + fields + |> Enum.map(&Map.get(@commit_fields, &1)) + |> Enum.join(@delimiter) + end + def create_pull_request do - {org, repo} = github_org_and_repo() + {:ok, {org, repo}} = github_org_and_repo() branch = current_branch() C.GitHub.API.get_pull_requests(org: org, repo: repo, head: branch, base: "master") end + def get_current_matching_pr() do + with {:ok, {org, repo}} <- github_org_and_repo(), + branch <- current_branch(), do: get_matching_pull_request(org, repo, "master", branch) + end + + def get_matching_pull_request(org, repo, base, branch) do + resp = C.GitHub.API.get_pull_requests(org: org, repo: repo, head: "#{org}:#{branch}", base: base) + with %{resp_body: [pr]} <- resp, do: pr + end + def github_org_and_repo() do - "git@github.com:" <> git_path = git_url("origin") - [org, repo] = git_path |> String.replace(~r/\.git$/, "") |> String.split("/") - {org, repo} + with "git@github.com:" <> git_path <- git_url("origin"), + [org, repo] <- git_path |> String.replace(~r/\.git$/, "") |> String.split("/") do + {:ok, {org, repo}} + else + _ -> {:error} + end end def git_url(remote_name) do @@ -28,11 +123,8 @@ defmodule C.Git do cmd_value("git", ["config", "--get", key]) end - def cmd_value(command, args) do - case System.cmd(command, args, cd: "/Users/venkat/Code/turtle/turtle-api") do - {value, 0} -> {:ok, String.trim(value)} - {err, 1} -> {:error, err} - end + def match_patterns(keywords) do + Enum.flat_map(keywords, fn k -> ["-e", k] end) end - + end diff --git a/lib/sloc.ex b/lib/sloc.ex index ddbabd2..af734a4 100644 --- a/lib/sloc.ex +++ b/lib/sloc.ex @@ -13,7 +13,7 @@ defmodule Sloc do end @path "../turtle/turtle-api/lib" - @whitelist ~w(.ex .exs .rb) + @whitelist ~w(.ex .exs .rb .js) def run do report = get_report(@path) diff --git a/lib/util.ex b/lib/util.ex new file mode 100644 index 0000000..6d0e640 --- /dev/null +++ b/lib/util.ex @@ -0,0 +1,17 @@ +defmodule C.Util do + + def cmd(command, args \\ []) do + case System.cmd(command, args, [into: IO.stream(:stdio, :line), stderr_to_stdout: true, parallelism: false]) do + {value, 0} -> {:ok, value} + {err, 1} -> {:error, err} + end + end + + def cmd_value(command, args) do + case System.cmd(command, args, [stderr_to_stdout: true]) do + {value, 0} -> {:ok, String.trim(value)} + {err, 1} -> {:error, err} + end + end + +end From 81704f33952957640d5c855cfbedef7bb00a597e Mon Sep 17 00:00:00 2001 From: Venkat Dinavahi Date: Tue, 29 Aug 2017 14:44:59 -0400 Subject: [PATCH 04/11] added ability to open a historical file in the editor --- config/config.exs | 2 ++ lib/cli.ex | 11 ++++++++--- lib/git.ex | 27 ++++++++++++++++++--------- lib/util.ex | 21 ++++++++++++--------- mix.exs | 3 ++- mix.lock | 1 + 6 files changed, 43 insertions(+), 22 deletions(-) diff --git a/config/config.exs b/config/config.exs index 28e00d4..7fefc73 100644 --- a/config/config.exs +++ b/config/config.exs @@ -15,3 +15,5 @@ config :revolver, "application/json" => Poison, "application/vnd.github.v3+json" => Poison } + +config :porcelain, driver: Porcelain.Driver.Basic \ No newline at end of file diff --git a/lib/cli.ex b/lib/cli.ex index 1ba1df1..137709f 100644 --- a/lib/cli.ex +++ b/lib/cli.ex @@ -1,5 +1,5 @@ defmodule C.CLI do - import C.Util, only: [cmd_value: 2, cmd: 1, cmd: 2] + import C.Util, only: [cmd: 2] def main(args) do {_opts, args, _} = OptionParser.parse(args) @@ -13,6 +13,9 @@ defmodule C.CLI do |> format_look() |> IO.puts() end + def execute("show", [commit_and_file]) do + C.Git.show_in_editor(commit_and_file) + end def execute("sloc", args) do report = Sloc.get_report(get_path(args)) IO.puts(Sloc.format_report(report)) @@ -21,12 +24,14 @@ defmodule C.CLI do C.GitHub.API.list!() end def execute("pr", _) do + %{"html_url" => url} = C.Git.get_current_matching_pr() + C.Util.open_in_browser(url) end def execute("branch", _) do args = ~w{for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'} cmd("git", ["status"]) end - def execute("pwd", _), do: cmd("pwd") + def execute("pwd", _), do: cmd("pwd", []) def get_path([]), do: File.cwd!() def get_path([path]), do: path @@ -36,7 +41,7 @@ defmodule C.CLI do end def format_entry(%{file: file, commit: %{hash: hash, author_date: author_date, subject: subject}, matches: matches}) do matches = Enum.map_join(matches, "\n", fn {line, text} -> to_string(line) <> ":" <> text end) - file <> ":" <> hash <> "\n" <> format_date(author_date) <> " " <> subject <> "\n" <> matches + hash <> ":" <> file <> "\n" <> format_date(author_date) <> " " <> subject <> "\n" <> matches end def format_date(date) do diff --git a/lib/git.ex b/lib/git.ex index 17897b0..aa45087 100644 --- a/lib/git.ex +++ b/lib/git.ex @@ -1,5 +1,5 @@ defmodule C.Git do - import C.Util, only: [cmd_value: 2] + import C.Util, only: [cmd: 2, open_in_editor: 1] defmodule Commit do defstruct [:hash, :subject, :body, @@ -11,16 +11,25 @@ defmodule C.Git do end def current_branch() do - {:ok, "refs/heads/" <> branch_name} = cmd_value("git", ["symbolic-ref", "HEAD"]) + {:ok, "refs/heads/" <> branch_name} = cmd("git", ["symbolic-ref", "HEAD"]) branch_name end - # @grep_opts ~w(--break --heading --line-number --ignore-case --color=always --all-match) + def show_in_editor(commit_with_file_path) do + [commit, file_path] = String.split(commit_with_file_path, ":", parts: 2) + tmp_dir = System.tmp_dir() + file_name = Path.basename(file_path) + tmp_file_path = Path.join(tmp_dir, file_name) + Porcelain.exec("git", ["show", commit_with_file_path], out: {:path, tmp_file_path}) + open_in_editor(tmp_file_path) + {:ok, tmp_file_path} + end + @grep_opts ~w(--ignore-case --all-match --heading --break --line-number) def search_history(keywords) do with {:ok, commits} <- list_commits(), commit_hashes <- Enum.map(commits, &Map.get(&1, :hash)), - {:ok, raw} <- cmd_value("git", ["grep"] ++ @grep_opts ++ match_patterns(keywords) ++ commit_hashes), + {:ok, raw} <- cmd("git", ["grep"] ++ @grep_opts ++ match_patterns(keywords) ++ commit_hashes), entries <- parse_search_history(raw, commits), do: filter_to_latest(entries) end @@ -51,7 +60,7 @@ defmodule C.Git do fields = [:hash, :author_date, :author_name, :subject] format = rev_parse_format(fields) filter = ["head"] - with {:ok, commit_string} <- cmd_value("git", ["rev-list"] ++ filter ++ ["--format=#{format}"]), + with {:ok, commit_string} <- cmd("git", ["rev-list"] ++ filter ++ ["--format=#{format}"]), do: {:ok, parse_commits(commit_string, fields)} end @@ -108,19 +117,19 @@ defmodule C.Git do [org, repo] <- git_path |> String.replace(~r/\.git$/, "") |> String.split("/") do {:ok, {org, repo}} else - _ -> {:error} + _ -> {:error, "failed to find org and repo for github project"} end end def git_url(remote_name) do - with {:ok, url} <- cmd_value("git", ["ls-remote", "--get-url", remote_name]), do: url + with {:ok, url} <- cmd("git", ["ls-remote", "--get-url", remote_name]), do: url end def set_config(key, value) do - cmd_value("git", ["config", "--global", key, value]) + cmd("git", ["config", "--global", key, value]) end def get_config(key) do - cmd_value("git", ["config", "--get", key]) + cmd("git", ["config", "--get", key]) end def match_patterns(keywords) do diff --git a/lib/util.ex b/lib/util.ex index 6d0e640..3b63b7c 100644 --- a/lib/util.ex +++ b/lib/util.ex @@ -1,17 +1,20 @@ defmodule C.Util do - def cmd(command, args \\ []) do - case System.cmd(command, args, [into: IO.stream(:stdio, :line), stderr_to_stdout: true, parallelism: false]) do - {value, 0} -> {:ok, value} - {err, 1} -> {:error, err} + @editor "code" + + def cmd(command, args) do + case Porcelain.exec(command, args, err: :out) do + %{status: 0, out: result} -> {:ok, String.trim(result)} + %{status: 1, out: err} -> {:error, err} end end - def cmd_value(command, args) do - case System.cmd(command, args, [stderr_to_stdout: true]) do - {value, 0} -> {:ok, String.trim(value)} - {err, 1} -> {:error, err} - end + def open_in_browser(url) do + cmd("open", [url]) end + def open_in_editor(path) do + cmd(@editor, [path]) + end + end diff --git a/mix.exs b/mix.exs index 90925e4..f8c0172 100644 --- a/mix.exs +++ b/mix.exs @@ -19,7 +19,8 @@ defmodule C.Mixfile do [ {:revolver, github: "scrogson/revolver", ref: "master"}, {:hackney, "1.6.1"}, - {:poison, "~> 3.0"} + {:poison, "~> 3.0"}, + {:porcelain, "~> 2.0"} ] end diff --git a/mix.lock b/mix.lock index 0b8360a..54f1a70 100644 --- a/mix.lock +++ b/mix.lock @@ -6,5 +6,6 @@ "mimerl": {:hex, :mimerl, "1.0.2", "993f9b0e084083405ed8252b99460c4f0563e41729ab42d9074fd5e52439be88", [:rebar3], []}, "plug": {:hex, :plug, "1.3.4", "b4ef3a383f991bfa594552ded44934f2a9853407899d47ecc0481777fb1906f6", [:mix], [{:cowboy, "~> 1.0.1 or ~> 1.1", [hex: :cowboy, optional: true]}, {:mime, "~> 1.0", [hex: :mime, optional: false]}]}, "poison": {:hex, :poison, "3.1.0", "d9eb636610e096f86f25d9a46f35a9facac35609a7591b3be3326e99a0484665", [:mix], []}, + "porcelain": {:hex, :porcelain, "2.0.3", "2d77b17d1f21fed875b8c5ecba72a01533db2013bd2e5e62c6d286c029150fdc", [], [], "hexpm"}, "revolver": {:git, "https://github.com/scrogson/revolver.git", "174f1049ba8beae65e53672b19d526bbba761a6d", [ref: "master"]}, "ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.0", "edee20847c42e379bf91261db474ffbe373f8acb56e9079acb6038d4e0bf414f", [:make, :rebar], []}} From 0be6daf5c8577974d302d192ac7800f9fbb580d4 Mon Sep 17 00:00:00 2001 From: Venkat Dinavahi Date: Fri, 22 Sep 2017 13:13:16 -0400 Subject: [PATCH 05/11] find command --- lib/cli.ex | 15 ++++++++++++--- lib/ex_uri.ex | 34 ++++++++++++++++++++++++++++++++++ lib/git.ex | 17 ++++++++++++++--- lib/sloc.ex | 12 +++++++++--- lib/util.ex | 10 ++++++---- 5 files changed, 75 insertions(+), 13 deletions(-) create mode 100644 lib/ex_uri.ex diff --git a/lib/cli.ex b/lib/cli.ex index 137709f..c1410a8 100644 --- a/lib/cli.ex +++ b/lib/cli.ex @@ -20,6 +20,11 @@ defmodule C.CLI do report = Sloc.get_report(get_path(args)) IO.puts(Sloc.format_report(report)) end + def execute("files", patterns) do + pattern = Enum.join([""] ++ patterns ++ [""], "*") + {:ok, matches} = C.Util.cmd("find", [".", "-type", "f", "-path", pattern]) + IO.puts(matches) + end def execute("req", _) do C.GitHub.API.list!() end @@ -27,9 +32,13 @@ defmodule C.CLI do %{"html_url" => url} = C.Git.get_current_matching_pr() C.Util.open_in_browser(url) end - def execute("branch", _) do - args = ~w{for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'} - cmd("git", ["status"]) + def execute("gh", ["search", language | keywords]) do + params = %{ + "type" => "Code", + "l" => language + } + search_uri = C.ExURI.merge_query_params("https://github.com/search", params) <> "&q=" <> Enum.join(keywords, "+") + C.Util.open_in_browser(search_uri) end def execute("pwd", _), do: cmd("pwd", []) diff --git a/lib/ex_uri.ex b/lib/ex_uri.ex new file mode 100644 index 0000000..85c99ec --- /dev/null +++ b/lib/ex_uri.ex @@ -0,0 +1,34 @@ +defmodule C.ExURI do + + def merge_query_params(%URI{query: nil}=uri, query_params) do + uri = %{uri | query: ""} + merge_query_params(uri, query_params) + end + def merge_query_params(%URI{query: query}=uri, query_params) do + new_query = query + |> URI.decode_query() + |> Map.merge(query_params) + |> URI.encode_query() + %{uri | query: new_query} + end + def merge_query_params(uri_string, query_params) when is_binary(uri_string) do + uri_string + |> URI.parse() + |> merge_query_params(query_params) + |> URI.to_string() + end + + def merge(uri, base, keys) when is_binary(uri) and is_binary(base) do + merge(URI.parse(uri), URI.parse(base), keys) + |> URI.to_string() + end + def merge(%URI{}=uri, %URI{}=base, keys) do + merge_map = Map.take(base, keys) + Map.merge(uri, merge_map, &merge_resolve/3) + end + + defp merge_resolve(_k, v1, nil), do: v1 + defp merge_resolve(_k, _v1, v2), do: v2 + + end + \ No newline at end of file diff --git a/lib/git.ex b/lib/git.ex index aa45087..5a76cd0 100644 --- a/lib/git.ex +++ b/lib/git.ex @@ -1,5 +1,5 @@ defmodule C.Git do - import C.Util, only: [cmd: 2, open_in_editor: 1] + import C.Util, only: [cmd: 2, cmd: 3, open_in_editor: 1] defmodule Commit do defstruct [:hash, :subject, :body, @@ -10,6 +10,16 @@ defmodule C.Git do defstruct [:commit, :file, :matches] end + def checkout(%{hash: hash}, dir), do: checkout(hash, dir) + def checkout(commit_hash, dir) when is_binary(commit_hash) do + Porcelain.exec("git", ["checkout", commit_hash], dir: dir) + end + + def reduce_over_commits(dir, reducer) do + {:ok, commits} = list_commits(dir) + Enum.reduce(commits, reducer) + end + def current_branch() do {:ok, "refs/heads/" <> branch_name} = cmd("git", ["symbolic-ref", "HEAD"]) branch_name @@ -56,11 +66,12 @@ defmodule C.Git do committer_email: "%ce", committer_name: "%cn"} @delimiter "$$;;" - def list_commits() do + def list_commits(), do: list_commits(File.cwd()) + def list_commits(dir) do fields = [:hash, :author_date, :author_name, :subject] format = rev_parse_format(fields) filter = ["head"] - with {:ok, commit_string} <- cmd("git", ["rev-list"] ++ filter ++ ["--format=#{format}"]), + with {:ok, commit_string} <- cmd("git", ["rev-list"] ++ filter ++ ["--format=#{format}"], [dir: dir]), do: {:ok, parse_commits(commit_string, fields)} end diff --git a/lib/sloc.ex b/lib/sloc.ex index af734a4..699d8ea 100644 --- a/lib/sloc.ex +++ b/lib/sloc.ex @@ -12,12 +12,18 @@ defmodule Sloc do end end - @path "../turtle/turtle-api/lib" + @path "/Users/venkat/Code/archive/turtle-api" @whitelist ~w(.ex .exs .rb .js) def run do - report = get_report(@path) - IO.puts(format_report(report)) + C.Git.checkout("master", @path) + {:ok, commits} = C.Git.list_commits(@path) |> IO.inspect() + for c <- commits, into: [] do + C.Git.checkout(c, @path) + report = get_report(@path <> "/lib") + line_count = report.line_count + {c.author_date, line_count} + end end def format_report(node), do: format_report(node, 0) diff --git a/lib/util.ex b/lib/util.ex index 3b63b7c..073d126 100644 --- a/lib/util.ex +++ b/lib/util.ex @@ -1,20 +1,22 @@ defmodule C.Util do @editor "code" + @browser "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" - def cmd(command, args) do - case Porcelain.exec(command, args, err: :out) do + def cmd(command, args, opts \\ []) do + opts = opts ++ [err: :out] + case Porcelain.exec(command, args, opts) do %{status: 0, out: result} -> {:ok, String.trim(result)} %{status: 1, out: err} -> {:error, err} end end def open_in_browser(url) do - cmd("open", [url]) + cmd(@browser, ["--args", url]) end def open_in_editor(path) do cmd(@editor, [path]) end - + end From aa3a8a68a4279dae7c7384caead010c4615ae715 Mon Sep 17 00:00:00 2001 From: Venkat Dinavahi Date: Tue, 26 Dec 2017 18:29:00 -0500 Subject: [PATCH 06/11] some tweaks --- lib/c.ex | 16 ---------------- lib/cli.ex | 5 +++++ lib/git.ex | 5 ++++- lib/play.ex | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 17 deletions(-) create mode 100644 lib/play.ex diff --git a/lib/c.ex b/lib/c.ex index 5b5c3e3..6919b44 100644 --- a/lib/c.ex +++ b/lib/c.ex @@ -1,18 +1,2 @@ defmodule C do - @moduledoc """ - Documentation for C. - """ - - @doc """ - Hello world. - - ## Examples - - iex> C.hello - :world - - """ - def hello do - :world - end end diff --git a/lib/cli.ex b/lib/cli.ex index c1410a8..5b1cf25 100644 --- a/lib/cli.ex +++ b/lib/cli.ex @@ -32,6 +32,11 @@ defmodule C.CLI do %{"html_url" => url} = C.Git.get_current_matching_pr() C.Util.open_in_browser(url) end + def execute("gh", []) do + {:ok, {org, repo}} = C.Git.github_org_and_repo() + uri = "https://github.com/#{org}/#{repo}" + C.Util.open_in_browser(uri) + end def execute("gh", ["search", language | keywords]) do params = %{ "type" => "Code", diff --git a/lib/git.ex b/lib/git.ex index 5a76cd0..729a272 100644 --- a/lib/git.ex +++ b/lib/git.ex @@ -66,7 +66,10 @@ defmodule C.Git do committer_email: "%ce", committer_name: "%cn"} @delimiter "$$;;" - def list_commits(), do: list_commits(File.cwd()) + def list_commits() do + {:ok, cwd} = File.cwd() + list_commits(cwd) + end def list_commits(dir) do fields = [:hash, :author_date, :author_name, :subject] format = rev_parse_format(fields) diff --git a/lib/play.ex b/lib/play.ex new file mode 100644 index 0000000..45877f4 --- /dev/null +++ b/lib/play.ex @@ -0,0 +1,51 @@ +defmodule Play do + @points [%{"end" => 14000, "message" => "And when the introduction keeps playing", + "start" => 11000}, +%{"end" => 18000, + "message" => "We go to the second transition of the introduction", + "start" => 14000}, +%{"end" => 22000, "message" => "We switch to the design section", + "start" => 18000}, +%{"end" => 26000, "message" => "And the design section will show a picture", + "start" => 22000}, +%{"end" => 30000, + "message" => "When I say the next word, we switch to the second picture", + "start" => 26000}, +%{"end" => 34000, "message" => "And then the third picture", "start" => 30000}, +%{"end" => 37000, "message" => "Then we switch to the architectural section", + "start" => 34000}, +%{"end" => 41000, "message" => "And you see a picture", "start" => 37000}, +%{"end" => 45000, + "message" => "And you talk a little bit more and there is a blog post", + "start" => 41000}, +%{"end" => 53000, + "message" => "If you scroll down to the blog post it pauses what I say", + "start" => 46000}, +%{"end" => 60000, + "message" => "Now that you scroll back up, I resume, and we keep talking", + "start" => 54000}, +%{"end" => 61000, "message" => "And we go to the roadmap section", + "start" => 60000}, +%{"end" => 66000, + "message" => "We're going through a little bit of a demo about the app model", + "start" => 62000}, +%{"end" => 69000, "message" => "There's some fancy animation", + "start" => 66000}, +%{"end" => 73000, "message" => "Talking about investors and paid users", + "start" => 69000}, +%{"end" => 78000, + "message" => "What happens when all of this goes horribly wrong", + "start" => 73000}] + + def run(base) do + origin(@points, base) + |> Enum.map(&Poison.encode!/1) + |> Enum.each(&IO.puts/1) + end + + def origin(points, origin) do + Enum.map(points, fn %{"start" => vstart, "end" => vend}=row -> + %{row | "start" => vstart - origin, "end" => vend - origin} + end) + end +end \ No newline at end of file From 436eb581f827587c2414055ce5d4a9cb76357f5c Mon Sep 17 00:00:00 2001 From: Venkat Dinavahi Date: Wed, 28 Mar 2018 18:24:12 -0400 Subject: [PATCH 07/11] start of git start command --- .gitignore | 1 + lib/cli.ex | 23 +++++++++++++++++++--- lib/ex_uri.ex | 7 +++---- lib/git.ex | 24 ++++++++++++++++------- lib/git/repo.ex | 46 ++++++++++++++++++++++++++++++++++++++++++++ lib/play.ex | 51 +------------------------------------------------ lib/util.ex | 9 +++++++++ 7 files changed, 97 insertions(+), 64 deletions(-) create mode 100644 lib/git/repo.ex diff --git a/.gitignore b/.gitignore index df81754..926de23 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ erl_crash.dump .DS_Store c +.elixir_ls \ No newline at end of file diff --git a/lib/cli.ex b/lib/cli.ex index 5b1cf25..87e2718 100644 --- a/lib/cli.ex +++ b/lib/cli.ex @@ -1,5 +1,5 @@ defmodule C.CLI do - import C.Util, only: [cmd: 2] + alias C.Git.Repo, as: Repo def main(args) do {_opts, args, _} = OptionParser.parse(args) @@ -8,6 +8,21 @@ defmodule C.CLI do execute(cmd, rest_args) end + def master_branch(), do: "master" + def origin, do: "origin" + + def repo(), do: Repo.new(dir: File.cwd!(), master_branch: master_branch()) + + def execute("start", branch_name_parts) do + branch_name = Enum.join(branch_name_parts, "-") + Repo.ensure_changes_committed!(repo()) + Repo.pull(repo(), origin(), master_branch()) + Repo.create_branch(repo(), branch_name, master_branch()) + end + def execute("branches", _) do + {:ok, branches} = C.Git.branch_names() + IO.inspect(branches) + end def execute("look", keywords) do C.Git.search_history(keywords) |> format_look() @@ -22,7 +37,7 @@ defmodule C.CLI do end def execute("files", patterns) do pattern = Enum.join([""] ++ patterns ++ [""], "*") - {:ok, matches} = C.Util.cmd("find", [".", "-type", "f", "-path", pattern]) + {:ok, matches} = C.Util.result("find", [".", "-type", "f", "-path", pattern]) IO.puts(matches) end def execute("req", _) do @@ -45,7 +60,9 @@ defmodule C.CLI do search_uri = C.ExURI.merge_query_params("https://github.com/search", params) <> "&q=" <> Enum.join(keywords, "+") C.Util.open_in_browser(search_uri) end - def execute("pwd", _), do: cmd("pwd", []) + def execute(name, _) do + raise "Unknown recognized command #{name}" + end def get_path([]), do: File.cwd!() def get_path([path]), do: path diff --git a/lib/ex_uri.ex b/lib/ex_uri.ex index 85c99ec..4df0753 100644 --- a/lib/ex_uri.ex +++ b/lib/ex_uri.ex @@ -1,5 +1,5 @@ defmodule C.ExURI do - + def merge_query_params(%URI{query: nil}=uri, query_params) do uri = %{uri | query: ""} merge_query_params(uri, query_params) @@ -29,6 +29,5 @@ defmodule C.ExURI do defp merge_resolve(_k, v1, nil), do: v1 defp merge_resolve(_k, _v1, v2), do: v2 - - end - \ No newline at end of file + +end diff --git a/lib/git.ex b/lib/git.ex index 729a272..e113b23 100644 --- a/lib/git.ex +++ b/lib/git.ex @@ -1,5 +1,5 @@ defmodule C.Git do - import C.Util, only: [cmd: 2, cmd: 3, open_in_editor: 1] + import C.Util, only: [cmd: 2, cmd: 3, result: 2, result: 3, open_in_editor: 1] defmodule Commit do defstruct [:hash, :subject, :body, @@ -25,8 +25,18 @@ defmodule C.Git do branch_name end + def branch_names() do + with {:ok, lines} <- result("git", ~w{for-each-ref --shell --format='%(refname)' refs/heads/}), + do: {:ok, String.split(lines, "\n") |> Enum.map(&clean_branch_name/1)} + end + def clean_branch_name(branch_name) do + branch_name + |> String.replace_prefix("''refs/heads/", "") + |> String.replace_suffix("''", "") + end + def show_in_editor(commit_with_file_path) do - [commit, file_path] = String.split(commit_with_file_path, ":", parts: 2) + [_commit, file_path] = String.split(commit_with_file_path, ":", parts: 2) tmp_dir = System.tmp_dir() file_name = Path.basename(file_path) tmp_file_path = Path.join(tmp_dir, file_name) @@ -39,7 +49,7 @@ defmodule C.Git do def search_history(keywords) do with {:ok, commits} <- list_commits(), commit_hashes <- Enum.map(commits, &Map.get(&1, :hash)), - {:ok, raw} <- cmd("git", ["grep"] ++ @grep_opts ++ match_patterns(keywords) ++ commit_hashes), + {:ok, raw} <- result("git", ["grep"] ++ @grep_opts ++ match_patterns(keywords) ++ commit_hashes), entries <- parse_search_history(raw, commits), do: filter_to_latest(entries) end @@ -74,7 +84,7 @@ defmodule C.Git do fields = [:hash, :author_date, :author_name, :subject] format = rev_parse_format(fields) filter = ["head"] - with {:ok, commit_string} <- cmd("git", ["rev-list"] ++ filter ++ ["--format=#{format}"], [dir: dir]), + with {:ok, commit_string} <- result("git", ["rev-list"] ++ filter ++ ["--format=#{format}"], [dir: dir]), do: {:ok, parse_commits(commit_string, fields)} end @@ -136,18 +146,18 @@ defmodule C.Git do end def git_url(remote_name) do - with {:ok, url} <- cmd("git", ["ls-remote", "--get-url", remote_name]), do: url + with {:ok, url} <- result("git", ["ls-remote", "--get-url", remote_name]), do: url end def set_config(key, value) do cmd("git", ["config", "--global", key, value]) end def get_config(key) do - cmd("git", ["config", "--get", key]) + result("git", ["config", "--get", key]) end def match_patterns(keywords) do Enum.flat_map(keywords, fn k -> ["-e", k] end) end - + end diff --git a/lib/git/repo.ex b/lib/git/repo.ex new file mode 100644 index 0000000..b88105b --- /dev/null +++ b/lib/git/repo.ex @@ -0,0 +1,46 @@ +defmodule C.Git.Repo do + defstruct [:dir, master_branch: "master"] + alias C.Git.Repo, as: R + import C.Util, only: [cmd: 2, cmd: 3, result: 2, result: 3, open_in_editor: 1] + + def new(opts), do: struct(R, opts) + + def pull(%R{dir: dir}, origin_name, branch_name) do + cmd("git", ["pull", origin_name, "#{branch_name}:#{branch_name}"], dir: dir) + end + + def create_branch(%R{dir: dir}, branch_name, source) do + cmd("git", ["checkout", "-b", branch_name, source], dir: dir) + end + def checkout_branch(%R{dir: dir}, branch_name) when is_binary(branch_name) do + cmd("git", ["checkout", branch_name], dir: dir) + end + + def ensure_changes_committed!(repo) do + case uncommitted_changes?(repo) do + true -> raise "You have uncommitted changes. Please stash them or commit them first." + false -> nil + end + end + + def checkout(%R{dir: dir}, %{hash: hash}), do: checkout(hash, dir) + def checkout(%R{dir: dir}, commit_hash) when is_binary(commit_hash) do + cmd("git", ["checkout", commit_hash], dir: dir) + end + + def uncommitted_changes?(%R{dir: dir}) do + case result("git", ["status", "--porcelain"], dir: dir) do + {:ok, v} when v != "" -> true + _ -> false + end + end + + def stash!(%R{dir: dir}) do + cmd("git", ["stash"], dir: dir) + end + + def stash_pop!(%R{dir: dir}) do + cmd("git", ["stash", "pop"], dir: dir) + end + +end diff --git a/lib/play.ex b/lib/play.ex index 45877f4..db26506 100644 --- a/lib/play.ex +++ b/lib/play.ex @@ -1,51 +1,2 @@ defmodule Play do - @points [%{"end" => 14000, "message" => "And when the introduction keeps playing", - "start" => 11000}, -%{"end" => 18000, - "message" => "We go to the second transition of the introduction", - "start" => 14000}, -%{"end" => 22000, "message" => "We switch to the design section", - "start" => 18000}, -%{"end" => 26000, "message" => "And the design section will show a picture", - "start" => 22000}, -%{"end" => 30000, - "message" => "When I say the next word, we switch to the second picture", - "start" => 26000}, -%{"end" => 34000, "message" => "And then the third picture", "start" => 30000}, -%{"end" => 37000, "message" => "Then we switch to the architectural section", - "start" => 34000}, -%{"end" => 41000, "message" => "And you see a picture", "start" => 37000}, -%{"end" => 45000, - "message" => "And you talk a little bit more and there is a blog post", - "start" => 41000}, -%{"end" => 53000, - "message" => "If you scroll down to the blog post it pauses what I say", - "start" => 46000}, -%{"end" => 60000, - "message" => "Now that you scroll back up, I resume, and we keep talking", - "start" => 54000}, -%{"end" => 61000, "message" => "And we go to the roadmap section", - "start" => 60000}, -%{"end" => 66000, - "message" => "We're going through a little bit of a demo about the app model", - "start" => 62000}, -%{"end" => 69000, "message" => "There's some fancy animation", - "start" => 66000}, -%{"end" => 73000, "message" => "Talking about investors and paid users", - "start" => 69000}, -%{"end" => 78000, - "message" => "What happens when all of this goes horribly wrong", - "start" => 73000}] - - def run(base) do - origin(@points, base) - |> Enum.map(&Poison.encode!/1) - |> Enum.each(&IO.puts/1) - end - - def origin(points, origin) do - Enum.map(points, fn %{"start" => vstart, "end" => vend}=row -> - %{row | "start" => vstart - origin, "end" => vend - origin} - end) - end -end \ No newline at end of file +end diff --git a/lib/util.ex b/lib/util.ex index 073d126..c291b5d 100644 --- a/lib/util.ex +++ b/lib/util.ex @@ -4,6 +4,15 @@ defmodule C.Util do @browser "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" def cmd(command, args, opts \\ []) do + opts = opts ++ [err: :out, out: IO.binstream(:standard_io, :line)] + IO.puts(Enum.join([command | args], " ")) + case Porcelain.exec(command, args, opts) do + %{status: 1} -> exit(:shutdown) + result -> result + end + end + + def result(command, args, opts \\ []) do opts = opts ++ [err: :out] case Porcelain.exec(command, args, opts) do %{status: 0, out: result} -> {:ok, String.trim(result)} From 75850764e1b5a800b5a5222daaca545ca399ad92 Mon Sep 17 00:00:00 2001 From: Venkat Dinavahi Date: Wed, 28 Mar 2018 18:34:52 -0400 Subject: [PATCH 08/11] c cancel --- lib/cli.ex | 6 ++++++ lib/git/repo.ex | 11 ++++++++++- lib/util.ex | 2 +- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/cli.ex b/lib/cli.ex index 87e2718..350fbac 100644 --- a/lib/cli.ex +++ b/lib/cli.ex @@ -19,6 +19,12 @@ defmodule C.CLI do Repo.pull(repo(), origin(), master_branch()) Repo.create_branch(repo(), branch_name, master_branch()) end + def execute("cancel", _) do + branch_to_delete = Repo.current_branch(repo()) + Repo.ensure_changes_committed!(repo()) + Repo.checkout_branch(repo(), master_branch()) + Repo.delete_branch(repo(), branch_to_delete) + end def execute("branches", _) do {:ok, branches} = C.Git.branch_names() IO.inspect(branches) diff --git a/lib/git/repo.ex b/lib/git/repo.ex index b88105b..8d858ae 100644 --- a/lib/git/repo.ex +++ b/lib/git/repo.ex @@ -1,7 +1,7 @@ defmodule C.Git.Repo do defstruct [:dir, master_branch: "master"] alias C.Git.Repo, as: R - import C.Util, only: [cmd: 2, cmd: 3, result: 2, result: 3, open_in_editor: 1] + import C.Util, only: [cmd: 2, cmd: 3, result: 2, result: 3] def new(opts), do: struct(R, opts) @@ -9,6 +9,11 @@ defmodule C.Git.Repo do cmd("git", ["pull", origin_name, "#{branch_name}:#{branch_name}"], dir: dir) end + def current_branch(%R{dir: dir}) do + {:ok, "refs/heads/" <> branch_name} = result("git", ["symbolic-ref", "HEAD"], dir: dir) + branch_name + end + def create_branch(%R{dir: dir}, branch_name, source) do cmd("git", ["checkout", "-b", branch_name, source], dir: dir) end @@ -16,6 +21,10 @@ defmodule C.Git.Repo do cmd("git", ["checkout", branch_name], dir: dir) end + def delete_branch(%R{dir: dir}, branch_name) do + cmd("git", ["branch", "-d", branch_name]) + end + def ensure_changes_committed!(repo) do case uncommitted_changes?(repo) do true -> raise "You have uncommitted changes. Please stash them or commit them first." diff --git a/lib/util.ex b/lib/util.ex index c291b5d..d980dcc 100644 --- a/lib/util.ex +++ b/lib/util.ex @@ -5,7 +5,7 @@ defmodule C.Util do def cmd(command, args, opts \\ []) do opts = opts ++ [err: :out, out: IO.binstream(:standard_io, :line)] - IO.puts(Enum.join([command | args], " ")) + IO.puts(IO.ANSI.green() <> Enum.join([command | args], " ") <> IO.ANSI.reset()) case Porcelain.exec(command, args, opts) do %{status: 1} -> exit(:shutdown) result -> result From 17ed23b7afe3e62393a39380672d39cf808bd342 Mon Sep 17 00:00:00 2001 From: Venkat Dinavahi Date: Fri, 19 Oct 2018 11:18:45 -0400 Subject: [PATCH 09/11] wip --- lib/cli.ex | 20 ++++++++++++++++++-- lib/git.ex | 16 ++++++++++++---- lib/git/repo.ex | 4 ++-- lib/github_api.ex | 3 +-- 4 files changed, 33 insertions(+), 10 deletions(-) diff --git a/lib/cli.ex b/lib/cli.ex index 350fbac..6b7c7ca 100644 --- a/lib/cli.ex +++ b/lib/cli.ex @@ -16,6 +16,8 @@ defmodule C.CLI do def execute("start", branch_name_parts) do branch_name = Enum.join(branch_name_parts, "-") Repo.ensure_changes_committed!(repo()) + + Repo.checkout(repo(), master_branch()) Repo.pull(repo(), origin(), master_branch()) Repo.create_branch(repo(), branch_name, master_branch()) end @@ -50,8 +52,22 @@ defmodule C.CLI do C.GitHub.API.list!() end def execute("pr", _) do - %{"html_url" => url} = C.Git.get_current_matching_pr() - C.Util.open_in_browser(url) + # C.GitHub.API.authorize!() + current_branch = C.Git.current_branch() + {:ok, {org, repo}} = C.Git.github_org_and_repo() + C.Git.push("origin", current_branch) + case C.Git.get_current_matching_pr() do + %{"html_url" => url} -> + C.Util.open_in_browser(url) + nil -> + C.GitHub.API.create_pull_request(%{ + org: org, + repo: repo, + base: master_branch(), + head: current_branch}) |> IO.inspect(label: :wtf) + %{"html_url" => url} = C.Git.get_current_matching_pr() + C.Util.open_in_browser(url) + end end def execute("gh", []) do {:ok, {org, repo}} = C.Git.github_org_and_repo() diff --git a/lib/git.ex b/lib/git.ex index e113b23..a8529d0 100644 --- a/lib/git.ex +++ b/lib/git.ex @@ -12,7 +12,11 @@ defmodule C.Git do def checkout(%{hash: hash}, dir), do: checkout(hash, dir) def checkout(commit_hash, dir) when is_binary(commit_hash) do - Porcelain.exec("git", ["checkout", commit_hash], dir: dir) + cmd("git", ["checkout", commit_hash], dir: dir) + end + + def push(origin, branch) do + cmd("git", ["push", origin, branch <> ":" <> branch]) end def reduce_over_commits(dir, reducer) do @@ -21,7 +25,7 @@ defmodule C.Git do end def current_branch() do - {:ok, "refs/heads/" <> branch_name} = cmd("git", ["symbolic-ref", "HEAD"]) + {:ok, "refs/heads/" <> branch_name} = result("git", ["symbolic-ref", "HEAD"]) branch_name end @@ -128,12 +132,16 @@ defmodule C.Git do def get_current_matching_pr() do with {:ok, {org, repo}} <- github_org_and_repo(), - branch <- current_branch(), do: get_matching_pull_request(org, repo, "master", branch) + branch <- current_branch(), + do: get_matching_pull_request(org, repo, "master", branch) end def get_matching_pull_request(org, repo, base, branch) do resp = C.GitHub.API.get_pull_requests(org: org, repo: repo, head: "#{org}:#{branch}", base: base) - with %{resp_body: [pr]} <- resp, do: pr + case resp.resp_body do + [pr] -> pr + _ -> nil + end end def github_org_and_repo() do diff --git a/lib/git/repo.ex b/lib/git/repo.ex index 8d858ae..ea45e4d 100644 --- a/lib/git/repo.ex +++ b/lib/git/repo.ex @@ -1,7 +1,7 @@ defmodule C.Git.Repo do defstruct [:dir, master_branch: "master"] alias C.Git.Repo, as: R - import C.Util, only: [cmd: 2, cmd: 3, result: 2, result: 3] + import C.Util, only: [cmd: 3, result: 3] def new(opts), do: struct(R, opts) @@ -22,7 +22,7 @@ defmodule C.Git.Repo do end def delete_branch(%R{dir: dir}, branch_name) do - cmd("git", ["branch", "-d", branch_name]) + cmd("git", ["branch", "-d", branch_name], dir: dir) end def ensure_changes_committed!(repo) do diff --git a/lib/github_api.ex b/lib/github_api.ex index 824dd40..a50ed8d 100644 --- a/lib/github_api.ex +++ b/lib/github_api.ex @@ -15,7 +15,7 @@ defmodule C.GitHub.API do def authorize! do auth = get_username_password() - response = authorize_req(auth) |> post!("/authorizations") + authorize_req(auth) |> post!("/authorizations") otp = IO.gets("Please specify two-factor auth code: ") |> String.trim() @@ -71,7 +71,6 @@ defmodule C.GitHub.API do end def get_username_password() do - # {"venkatd", "9gbAQFPhFhQqp2"} username = IO.gets("username: ") password = IO.gets("password: ") {String.trim(username), String.trim(password)} From 85d5ba8537333335b239fff2cefe63029e64692a Mon Sep 17 00:00:00 2001 From: Venkat Dinavahi Date: Fri, 19 Oct 2018 13:04:22 -0400 Subject: [PATCH 10/11] added clean command --- lib/cli.ex | 32 ++++++++++++++++++++++++-------- lib/git.ex | 33 ++++++++++----------------------- lib/git/repo.ex | 25 ++++++++++++++++++++++++- lib/github_api.ex | 6 +++--- lib/util.ex | 6 ++++++ 5 files changed, 67 insertions(+), 35 deletions(-) diff --git a/lib/cli.ex b/lib/cli.ex index 6b7c7ca..4f541f4 100644 --- a/lib/cli.ex +++ b/lib/cli.ex @@ -2,16 +2,22 @@ defmodule C.CLI do alias C.Git.Repo, as: Repo def main(args) do - {_opts, args, _} = OptionParser.parse(args) + {_opts, args, _} = OptionParser.parse(args, allow_nonexistent_atoms: true) [cmd | rest_args] = args execute(cmd, rest_args) end - def master_branch(), do: "master" + def master_branch, do: "master" def origin, do: "origin" - def repo(), do: Repo.new(dir: File.cwd!(), master_branch: master_branch()) + def repo do + Repo.new( + dir: System.get_env("DIR") || File.cwd(), + master_branch: master_branch(), + protected_branches: ["master", "development"] + ) + end def execute("start", branch_name_parts) do branch_name = Enum.join(branch_name_parts, "-") @@ -28,9 +34,18 @@ defmodule C.CLI do Repo.delete_branch(repo(), branch_to_delete) end def execute("branches", _) do - {:ok, branches} = C.Git.branch_names() + {:ok, branches} = Repo.branches(repo()) IO.inspect(branches) end + def execute("clean", _) do + merged_branches = Repo.merged_branches(repo(), master_branch()) + IO.puts("These branches have already been merged:") + IO.puts(Enum.join(merged_branches, " ")) + IO.puts("Deleting them...") + Enum.each(merged_branches, fn branch -> + Repo.delete_branch(repo(), branch) + end) + end def execute("look", keywords) do C.Git.search_history(keywords) |> format_look() @@ -53,10 +68,10 @@ defmodule C.CLI do end def execute("pr", _) do # C.GitHub.API.authorize!() - current_branch = C.Git.current_branch() + current_branch = Repo.current_branch(repo()) {:ok, {org, repo}} = C.Git.github_org_and_repo() C.Git.push("origin", current_branch) - case C.Git.get_current_matching_pr() do + case C.Git.get_current_matching_pr(repo()) do %{"html_url" => url} -> C.Util.open_in_browser(url) nil -> @@ -64,8 +79,9 @@ defmodule C.CLI do org: org, repo: repo, base: master_branch(), - head: current_branch}) |> IO.inspect(label: :wtf) - %{"html_url" => url} = C.Git.get_current_matching_pr() + title: C.Util.humanize(current_branch), + head: current_branch}) + %{"html_url" => url} = C.Git.get_current_matching_pr(repo()) C.Util.open_in_browser(url) end end diff --git a/lib/git.ex b/lib/git.ex index a8529d0..c4aaac4 100644 --- a/lib/git.ex +++ b/lib/git.ex @@ -1,4 +1,6 @@ defmodule C.Git do + alias C.Git.Repo, as: R + import C.Util, only: [cmd: 2, cmd: 3, result: 2, result: 3, open_in_editor: 1] defmodule Commit do @@ -24,21 +26,6 @@ defmodule C.Git do Enum.reduce(commits, reducer) end - def current_branch() do - {:ok, "refs/heads/" <> branch_name} = result("git", ["symbolic-ref", "HEAD"]) - branch_name - end - - def branch_names() do - with {:ok, lines} <- result("git", ~w{for-each-ref --shell --format='%(refname)' refs/heads/}), - do: {:ok, String.split(lines, "\n") |> Enum.map(&clean_branch_name/1)} - end - def clean_branch_name(branch_name) do - branch_name - |> String.replace_prefix("''refs/heads/", "") - |> String.replace_suffix("''", "") - end - def show_in_editor(commit_with_file_path) do [_commit, file_path] = String.split(commit_with_file_path, ":", parts: 2) tmp_dir = System.tmp_dir() @@ -124,16 +111,16 @@ defmodule C.Git do |> Enum.join(@delimiter) end - def create_pull_request do - {:ok, {org, repo}} = github_org_and_repo() - branch = current_branch() - C.GitHub.API.get_pull_requests(org: org, repo: repo, head: branch, base: "master") + def create_pull_request(repo) do + {:ok, {org, repo_name}} = github_org_and_repo() + branch = R.current_branch(repo) + C.GitHub.API.get_pull_requests(org: org, repo: repo_name, head: branch, base: "master") end - def get_current_matching_pr() do - with {:ok, {org, repo}} <- github_org_and_repo(), - branch <- current_branch(), - do: get_matching_pull_request(org, repo, "master", branch) + def get_current_matching_pr(repo) do + with {:ok, {org, repo_name}} <- github_org_and_repo(), + branch <- R.current_branch(repo), + do: get_matching_pull_request(org, repo_name, "master", branch) end def get_matching_pull_request(org, repo, base, branch) do diff --git a/lib/git/repo.ex b/lib/git/repo.ex index ea45e4d..ada7a90 100644 --- a/lib/git/repo.ex +++ b/lib/git/repo.ex @@ -1,5 +1,5 @@ defmodule C.Git.Repo do - defstruct [:dir, master_branch: "master"] + defstruct [:dir, master_branch: "master", protected_branches: []] alias C.Git.Repo, as: R import C.Util, only: [cmd: 3, result: 3] @@ -25,6 +25,29 @@ defmodule C.Git.Repo do cmd("git", ["branch", "-d", branch_name], dir: dir) end + def branches(%R{dir: dir}) do + with {:ok, lines} <- result("git", ["for-each-ref", "--shell", "--format='%(refname)'", "refs/heads/"], dir: dir), + do: {:ok, parse_branch_list(lines)} + end + def merged_branches(%R{dir: dir, protected_branches: protected_branches}, base_branch) do + with {:ok, lines} <- result("git", ["for-each-ref", "--shell", "--merged", base_branch, "--format='%(refname)'", "refs/heads/"], dir: dir) do + branches = parse_branch_list(lines) + List.delete(branches, base_branch) -- protected_branches + end + end + + defp parse_branch_list(text) do + text + |> String.trim() + |> String.split("\n") + |> Enum.map(&clean_branch_name/1) + end + defp clean_branch_name(branch_name) do + branch_name + |> String.replace_prefix("''refs/heads/", "") + |> String.replace_suffix("''", "") + end + def ensure_changes_committed!(repo) do case uncommitted_changes?(repo) do true -> raise "You have uncommitted changes. Please stash them or commit them first." diff --git a/lib/github_api.ex b/lib/github_api.ex index a50ed8d..d7fb334 100644 --- a/lib/github_api.ex +++ b/lib/github_api.ex @@ -41,10 +41,10 @@ defmodule C.GitHub.API do opts = Enum.into(opts, %{}) do_create_pull_request(opts) end - def do_create_pull_request(%{org: org, repo: repo, base: base, head: head}) do + def do_create_pull_request(%{title: title, org: org, repo: repo, base: base, head: head}) do params = %{ - "title" => "Amazing new feature", - "body" => "Please pull this in!", + "title" => title, + "body" => "", "head" => head, "base" => base } diff --git a/lib/util.ex b/lib/util.ex index d980dcc..bf8114f 100644 --- a/lib/util.ex +++ b/lib/util.ex @@ -3,6 +3,12 @@ defmodule C.Util do @editor "code" @browser "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" + def humanize(branch_name) do + branch_name + |> String.replace("-", " ") + |> String.capitalize() + end + def cmd(command, args, opts \\ []) do opts = opts ++ [err: :out, out: IO.binstream(:standard_io, :line)] IO.puts(IO.ANSI.green() <> Enum.join([command | args], " ") <> IO.ANSI.reset()) From 7d7bbbf7c18e8d50c341ff0311bddd32d0cf2206 Mon Sep 17 00:00:00 2001 From: Venkat Dinavahi Date: Fri, 19 Oct 2018 13:34:36 -0400 Subject: [PATCH 11/11] removed inspect --- lib/cli.ex | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/cli.ex b/lib/cli.ex index 4f541f4..9526e7d 100644 --- a/lib/cli.ex +++ b/lib/cli.ex @@ -13,7 +13,7 @@ defmodule C.CLI do def repo do Repo.new( - dir: System.get_env("DIR") || File.cwd(), + dir: System.get_env("DIR") || File.cwd!(), master_branch: master_branch(), protected_branches: ["master", "development"] )