aboutsummaryrefslogtreecommitdiff
path: root/hooked/src/main.rs
blob: 573061c244f8a24741962d5e14a6e55175c3b07a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
//! git hook manager tool

use anyhow::{
  bail,
  Result,
};
use log::*;
use shared::find_root;
#[cfg(not(windows))]
use std::os::unix::fs::{
  symlink,
  PermissionsExt,
};
#[cfg(windows)]
use std::os::windows::fs::symlink_file;
use std::{
  env,
  fs,
  io::Write,
  path::Path,
};

const HOOKS: [&str; 18] = [
  "applypatch-msg",
  "post-applypatch",
  "pre-commit",
  "prepare-commit-msg",
  "commit-msg",
  "post-commit",
  "pre-rebase",
  "post-checkout",
  "post-merge",
  "pre-push",
  "pre-receive",
  "update",
  "post-receive",
  "post-update",
  "push-to-checkout",
  "pre-auto-gc",
  "post-rewrite",
  "sendemail-validate",
];

#[derive(structopt::StructOpt)]
enum Args {
  /// Initialize the repo to use hooked
  Init(Language),
  /// Link pre existing hooks to your .git folder
  Link,
}

/// Which language the repo should be initialized with for hooks
#[derive(Clone, Copy, structopt::StructOpt)]
enum Language {
  /// Use Bash for your git hooks
  Bash,
  /// Use Python 3 for your git hooks
  Python,
  /// Use Ruby for your git hooks
  Ruby,
}

#[paw::main]
fn main(args: Args) {
  env::var("RUST_LOG")
    .ok()
    .map_or_else(|| env::set_var("RUST_LOG", "info"), drop);
  pretty_env_logger::init();
  if let Err(e) = match args {
    Args::Init(lang) => init(lang),
    Args::Link => link(),
  } {
    error!("{}", e);
    std::process::exit(1);
  }
}

fn init(lang: Language) -> Result<()> {
  let root = find_root()?;
  let git_hooks = &root.join(".git").join("hooks");
  debug!("git_hooks base path: {}", git_hooks.display());
  let root = root.join(".dev-suite").join("hooked");
  debug!("root base path: {}", root.display());
  let wrapper_dir = &root.join("wrapper");
  fs::create_dir_all(&wrapper_dir)?;

  for hook in &HOOKS {
    let mut path = (&root).join(hook);
    debug!("dev-suite hook path: {}", path.display());
    let git_hook = &git_hooks.join(hook);
    debug!("git_hook path: {}", git_hook.display());
    let mut wrapper_hook = (&wrapper_dir).join(hook);
    let _ = wrapper_hook.set_extension("sh");
    let _ = match lang {
      Language::Bash => path.set_extension("sh"),
      Language::Python => path.set_extension("py"),
      Language::Ruby => path.set_extension("rb"),
    };

    if path.exists() {
      debug!("git hook {} already exists. Skipping creation.", hook);
    } else {
      debug!("Creating dev-suite hook.");
      let mut file = fs::File::create(&path)?;
      let mut wrapper = fs::File::create(&wrapper_hook)?;
      trace!("File created.");
      #[cfg(not(windows))]
      {
        let mut perms = file.metadata()?.permissions();
        let mut wrapper_perms = wrapper.metadata()?.permissions();
        debug!("Setting dev-suite hook to be executable.");
        perms.set_mode(0o755);
        wrapper_perms.set_mode(0o755);
        file.set_permissions(perms)?;
        wrapper.set_permissions(wrapper_perms)?;
        trace!("Permissions were set.");
      }
      match lang {
        Language::Bash => {
          file.write_all(b"#!/usr/bin/env bash")?;
          wrapper.write_all(
            format!(
              "#!C:\\Program Files\\Git\\bin\\sh.exe\n\
               bash.exe .dev-suite/hooked/{}.sh\n",
              hook
            )
            .as_bytes(),
          )?;
        }
        Language::Python => {
          file.write_all(b"#!/usr/bin/env python3")?;
          wrapper.write_all(
            format!(
              "#!C:\\Program Files\\Git\\bin\\sh.exe\n\
               py.exe .dev-suite/hooked/{}.py\n",
              hook
            )
            .as_bytes(),
          )?;
        }
        Language::Ruby => {
          file.write_all(b"#!/usr/bin/env ruby")?;
          wrapper.write_all(
            format!(
              "#!C:\\Program Files\\Git\\bin\\sh.exe\n\
               ruby.exe .dev-suite/hooked/{}.rb\n",
              hook
            )
            .as_bytes(),
          )?;
        }
      }
      debug!("Writing data to file.");
      debug!("Created git hook {}.", hook);
    }

    #[cfg(not(windows))]
    let link_path = path.canonicalize()?;
    #[cfg(windows)]
    let link_path = wrapper_hook.canonicalize()?;

    inner_link(&link_path, &git_hook, hook)?;
  }
  info!(
    "Created and symlinked tickets to .git/hooks from {}.",
    root.display()
  );
  #[cfg(windows)]
  {
    warn!("Make sure to add the hooks into git with 'git add --chmod=+x .dev-suite\\hooked'");
    warn!("If you don't they won't be set as executable on unix systems");
  }

  Ok(())
}

fn link() -> Result<()> {
  let root = find_root()?;
  let git_hooks = &root.join(".git").join("hooks");
  debug!("git_hooks base path: {}", git_hooks.display());
  let root = root.join(".dev-suite").join("hooked");
  debug!("root base path: {}", root.display());

  for hook in &HOOKS {
    let path = {
      #[cfg(windows)]
      let mut path = root.join("wrapper").join(hook);
      #[cfg(not(windows))]
      let mut path = root.join(hook);
      debug!("PATH: {}", path.display());

      let mut path_python = path.clone();
      let _ = path_python.set_extension("py");
      let mut path_ruby = path.clone();
      let _ = path_ruby.set_extension("rb");
      let mut path_bash = path.clone();
      let _ = path_bash.set_extension("sh");

      if path_python.exists() {
        path_python
      } else if path_ruby.exists() {
        path_ruby
      } else if path_bash.exists() {
        path_bash
      } else {
        let _ = path.set_extension("");
        bail!(
          "The path {} does not exist. Have you initialized the repo to use hooked?",
          path.display()
        );
      }
    };
    let path = path.canonicalize()?;
    debug!("dev-suite hook path: {}", path.display());
    let git_hook = &git_hooks.join(hook);
    debug!("git_hook path: {}", git_hook.display());
    inner_link(&path, &git_hook, hook)?;
  }

  info!("Successfully symlinked all githooks to .git/hooks");
  Ok(())
}

fn inner_link(path: &Path, git_hook: &Path, hook: &str) -> Result<()> {
  if !git_hook.exists() {
    debug!("Symlinking git hook {}.", hook);
    #[cfg(not(windows))]
    symlink(&path, &git_hook)?;
    #[cfg(windows)]
    symlink_file(&path, &git_hook)?;
    debug!(
      "Symlinked git hook {} to {}",
      git_hook.display(),
      path.display()
    );
  }
  Ok(())
}