Friday 19 May 2017

How to programmatically git checkout a file partially

Here is what I'm doing. add a pre-commit hook using npm scripts, an example repo

"is-commitable": "git status | grep 'Changes to be committed:'",
"stash-pop": "git stash pop >> /dev/null",
"stash-unstaged": "git stash save -k --include-untracked 'unstaged-stash' >> /dev/null",
"check-commitable": "npm run is-commitable || (npm run stash-pop && exit 1)",
"lint-staged": "(eslint . --fix && git add .) || (npm run stash-pop && exit 1)",
"recheck-commitable": "npm run check-commitable",
"stash-linted": "git stash save 'linted-stash' >> /dev/null",
"stash-pop-unstaged": "git stash pop stash@{1}",
"stash-pop-linted": "git read-tree stash && git stash drop",
"clean-lint-staged": "(lint-staged >> /dev/null) || exit 0"

Example

  1. have two lines of commited code:

    line1
    line2
    
    
  2. make some changes:

    * line1-changed
    * line2-changed
    
    
  3. partially add one of them:

    - line1
    + line1-changed
    * line2-changed
    
    
  4. run commit and pre-commit hook is triggered

    • stash-unstaged

      - line1
      + line1-changed
      line2(changed part been stashed in unstaged-stash)
      
      
    • lint-staged

      - line1
      + line1-fixed
      line2(changed part been stashed in unstaged-stash)
      
      
    • stash-linted

      line1(changed and fixed part been stashed in linted-stash)
      line2(changed part been stashed in unstaged-stash)
      
      
    • stash-pop-unstaged

      line1(changed and fixed part been stashed in linted-stash)
      * line2-changed
      
      
    • stash-pop-linted

      - line1
      + line1-fixed
      * line1-changed
      * line2-changed
      
      
    • clean-lint-staged

      - line1
      + line1-fixed
      * line2-fixed
      
      

Problem

The last 2 steps are not perfect.

Expected result

I wanted to get

- line1
+ line1-fixed
* line2-changed

Actual results

But now I can only get

- line1
+ line1-fixed
* line1-changed
* line2-changed

or

- line1
+ line1-fixed
* line2-fixed

Need help

So can I find a way to programmatically git checkout a file only the staged lines?

Or drop the last step find a way to fix the last 2nd step



via Stupidism

No comments:

Post a Comment