diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..926de23 --- /dev/null +++ b/.gitignore @@ -0,0 +1,22 @@ +# 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 +.elixir_ls \ No newline at end of file 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/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 index 93d77b6..be551de 100644 --- a/README.md +++ b/README.md @@ -1,70 +1,19 @@ -[![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) +# C -Code: The Coderly Toolbelt -================== +**TODO: Add description** -`code` is a command line tool that automates our Coderly development workflow. +## Installation -`code` is best aliased as `c`, so you can type `$ c ` in the shell. +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 +``` -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. +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). -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/config/config.exs b/config/config.exs new file mode 100644 index 0000000..7fefc73 --- /dev/null +++ b/config/config.exs @@ -0,0 +1,19 @@ +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 + } + +config :porcelain, driver: Porcelain.Driver.Basic \ No newline at end of file diff --git a/lib/c.ex b/lib/c.ex new file mode 100644 index 0000000..6919b44 --- /dev/null +++ b/lib/c.ex @@ -0,0 +1,2 @@ +defmodule C do +end diff --git a/lib/cli.ex b/lib/cli.ex new file mode 100644 index 0000000..9526e7d --- /dev/null +++ b/lib/cli.ex @@ -0,0 +1,121 @@ +defmodule C.CLI do + alias C.Git.Repo, as: Repo + + def main(args) do + {_opts, args, _} = OptionParser.parse(args, allow_nonexistent_atoms: true) + + [cmd | rest_args] = args + execute(cmd, rest_args) + end + + def master_branch, do: "master" + def origin, do: "origin" + + 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, "-") + 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 + 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} = 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() + |> 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)) + end + def execute("files", patterns) do + pattern = Enum.join([""] ++ patterns ++ [""], "*") + {:ok, matches} = C.Util.result("find", [".", "-type", "f", "-path", pattern]) + IO.puts(matches) + end + def execute("req", _) do + C.GitHub.API.list!() + end + def execute("pr", _) do + # C.GitHub.API.authorize!() + 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(repo()) do + %{"html_url" => url} -> + C.Util.open_in_browser(url) + nil -> + C.GitHub.API.create_pull_request(%{ + org: org, + repo: repo, + base: master_branch(), + 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 + 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", + "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(name, _) do + raise "Unknown recognized command #{name}" + end + + def get_path([]), do: File.cwd!() + def get_path([path]), do: path + + def format_look(entries) do + Enum.map_join(entries, "\n\n", &format_entry/1) + 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) + hash <> ":" <> file <> "\n" <> format_date(author_date) <> " " <> subject <> "\n" <> matches + end + + def format_date(date) do + [date, _time] = String.split(date, "T", parts: 2) + date + end + +end 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/lib/ex_uri.ex b/lib/ex_uri.ex new file mode 100644 index 0000000..4df0753 --- /dev/null +++ b/lib/ex_uri.ex @@ -0,0 +1,33 @@ +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 diff --git a/lib/git.ex b/lib/git.ex new file mode 100644 index 0000000..c4aaac4 --- /dev/null +++ b/lib/git.ex @@ -0,0 +1,158 @@ +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 + 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 checkout(%{hash: hash}, dir), do: checkout(hash, dir) + def checkout(commit_hash, dir) when is_binary(commit_hash) do + 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 + {:ok, commits} = list_commits(dir) + Enum.reduce(commits, reducer) + 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() + 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} <- result("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 + {: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) + filter = ["head"] + with {:ok, commit_string} <- result("git", ["rev-list"] ++ filter ++ ["--format=#{format}"], [dir: dir]), + 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(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(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 + resp = C.GitHub.API.get_pull_requests(org: org, repo: repo, head: "#{org}:#{branch}", base: base) + case resp.resp_body do + [pr] -> pr + _ -> nil + end + end + + def github_org_and_repo() do + 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, "failed to find org and repo for github project"} + end + end + + def git_url(remote_name) do + 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 + 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..ada7a90 --- /dev/null +++ b/lib/git/repo.ex @@ -0,0 +1,78 @@ +defmodule C.Git.Repo do + defstruct [:dir, master_branch: "master", protected_branches: []] + alias C.Git.Repo, as: R + import C.Util, only: [cmd: 3, result: 3] + + 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 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 + def checkout_branch(%R{dir: dir}, branch_name) when is_binary(branch_name) do + cmd("git", ["checkout", branch_name], dir: dir) + end + + def delete_branch(%R{dir: dir}, branch_name) 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." + 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/github_api.ex b/lib/github_api.ex new file mode 100644 index 0000000..d7fb334 --- /dev/null +++ b/lib/github_api.ex @@ -0,0 +1,83 @@ +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() + 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(%{title: title, org: org, repo: repo, base: base, head: head}) do + params = %{ + "title" => title, + "body" => "", + "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 + 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/play.ex b/lib/play.ex new file mode 100644 index 0000000..db26506 --- /dev/null +++ b/lib/play.ex @@ -0,0 +1,2 @@ +defmodule Play do +end diff --git a/lib/sloc.ex b/lib/sloc.ex new file mode 100644 index 0000000..699d8ea --- /dev/null +++ b/lib/sloc.ex @@ -0,0 +1,105 @@ +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 "/Users/venkat/Code/archive/turtle-api" + @whitelist ~w(.ex .exs .rb .js) + + def run do + 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) + 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/lib/util.ex b/lib/util.ex new file mode 100644 index 0000000..bf8114f --- /dev/null +++ b/lib/util.ex @@ -0,0 +1,37 @@ +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()) + 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)} + %{status: 1, out: err} -> {:error, err} + end + end + + def open_in_browser(url) do + cmd(@browser, ["--args", url]) + end + + def open_in_editor(path) do + cmd(@editor, [path]) + end + +end diff --git a/mix.exs b/mix.exs new file mode 100644 index 0000000..f8c0172 --- /dev/null +++ b/mix.exs @@ -0,0 +1,27 @@ +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"}, + {:porcelain, "~> 2.0"} + ] + end + +end diff --git a/mix.lock b/mix.lock new file mode 100644 index 0000000..54f1a70 --- /dev/null +++ b/mix.lock @@ -0,0 +1,11 @@ +%{"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], []}, + "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], []}} 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 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()